Unity 基础

unity是一个轻量级ioc容器,它为方便开发者建立松散耦合的应用程序,可以在 http://unity.codeplex.com/ 下载获取

一个简单的日志功能的配置:

日志类和接口:

    public interface ILog

    {

        void LogMessage(string msg);

    }



    class LocalLog : ILog

    {

        public void LogMessage(string msg)

        {

            Console.WriteLine("LocalLog..." + msg);

        }

    }



    public class RemoteLog : ILog

    {

        public void LogMessage(string msg)

        {

            Console.WriteLine("RemoteLog...." + msg);

        }

    }

注册和调用:

    class Program

    {

        static void Main(string[] args)

        {

            IUnityContainer unityContainer = new UnityContainer();

            //注册映射

            unityContainer.RegisterType<ILog, LocalLog>("local")

                          .RegisterType<ILog, RemoteLog>("remote");





            var localLog = unityContainer.Resolve<ILog>("local");

            localLog.LogMessage("msg1");



            //构造函数参数传入

            //可以直接传入一个IEnumerable类型的ParameterOverrides,也可以多个ParameterOverride

            //都是key,value的形式

            var t = unityContainer.Resolve<TestLog>(  new ParameterOverrides { 

                        { "param", "yyy" } 

                    });



           //也可以这样传入参数

           //unityContainer.Resolve<TestLog>(new ParameterOverride("param", "xxx"));



            //通过Dependency特性属性注入

           t.LogService.LogMessage("error1");



           Console.WriteLine(t.Param);

        }

    }



    class TestLog

    {

        [Dependency("remote")]

        public ILog LogService { get; set; }



        public string Param { get; set; }

        public TestLog(string param)

        {

            Param = param;

        }

    }

你可能感兴趣的:(unity)