Unity 依赖注入之一

在项目中引入Unity,建立一个接口IWork跟一个继承IWork接口的Work类

    public interface IMyWork
    {
        void Work();
    }
    public class MyWork : IMyWork
    {
        public void Work()
        {
            Console.WriteLine("Hello World!");
        }
    }

unity的简单使用分三步

        static void Main(string[] args)
        {
            UnityContainer container = new UnityContainer();//创建IOC容器
            container.RegisterType<IMyWork, MyWork>();//注册(Register)
            var myWork = container.Resolve<IMyWork>();//获取(Resolve)
            myWork.Work();//hello world
            Console.ReadKey();
        }

参考Unity ASP.NET MVC 将UnityContaniner封装 类名也叫做UnityConfig(参考Unity4.0的使用),进行职责分离,分离注册与获取,同时进行单例与延迟加载(在后面的文章还会提到)

  public class UnityConfig : IInstance<UnityConfig>, IServiceProvider
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            //container.LoadConfiguration();

            // TODO: Register your types here
            // container.RegisterType<IProductRepository, ProductRepository>();
            container.RegisterType<IMyWork, MyWork>();
        }

        public object GetService(Type serviceType)
        {
            return GetConfiguredContainer().Resolve(serviceType);
        }

        public T GetService<T>()
        {
            return (T)GetService(typeof(T));
        }
    }
    public class IInstance<T> where T : new()
    {
        private static readonly T instance = new T();

        public static T Instance
        {
            get { return instance; }
        }
    }

最后的调用

    class Program
    {
        static void Main(string[] args)
        {
            var myWork = UnityConfig.Instance.GetService<IMyWork>();//获取(Resolve)

            myWork.Work();//hello world

            Console.ReadKey();
        }
    }

 

以上是本人比较初级的处理,主要用于本人学习Unity的一个记录

 

你可能感兴趣的:(Unity 依赖注入之一)