Unity调用方法注入

接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace UnityDemo3
{
    public interface ISqlMapper
    {
        void Alert();
    }
}

sqlMapper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UnityDemo3
{
    public class SqlMapper:ISqlMapper
    {

        public void Alert()
        {
            Console.WriteLine("This is SqlMapper");
        }
    }
}

基类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

namespace UnityDemo3
{
    public class BaseClass
    {

        public BaseClass()
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterType();
            container.BuildUp(this.GetType(), this);
        }
    }
}

子类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

namespace UnityDemo3
{
    public class ChildClass : BaseClass
    {
        private  ISqlMapper iSqlMapper;

        
        public ChildClass()
        {
        }
        
        
        [InjectionMethod]
        public void Init(ISqlMapper isql) 
        {
            iSqlMapper =isql;
        }

        public void Alert()
        {
            iSqlMapper.Alert();
        }
    }
}

主程序


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UnityDemo3
{
    class Program
    {
        static void Main(string[] args)
        {
            ChildClass c = new ChildClass();
            c.Alert();

            Console.ReadKey();
        }
    }
}










你可能感兴趣的:(Unity调用方法注入)