最新源代码:https://github.com/unitycontainer/unity
Unity是轻量级、可扩展的依赖注入容器,用于对框架的解耦和增强可扩展性。Unity生于微软。想了解IOC的前世今生可以看下Spring.NET。
一、MVC使用Unity
1.使用
先不管Unity,新建类库,随便写几个Service
public interface IArticleService { string GetArticle(); } ------ public class ArticleService:IArticleService { public string GetArticle() { return "sso"; } }
首先在MVC项目上安装NuGet包:Unity.Mvc
安装完成后会在MVC项目的App_Start文件中看到自动加入了两个文件:UnityConfig.cs、UnityMvcActivator.cs;后者的作用可以看前文:动态注册Httpmodule;
这个时候我们注册类型到IOC容器
using System; using Practice.IocUnity.Service; using Practice.IocUnity.Service.Interface; using Unity; using Unity.Lifetime; namespace Practice.IocUnity.Web { /// <summary> /// Specifies the Unity configuration for the main container. /// </summary> public static class UnityConfig { #region Unity Container private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => { var container = new UnityContainer(); RegisterTypes(container); return container; }); /// <summary> /// Configured Unity Container. /// </summary> public static IUnityContainer Container => 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 Unity.Configuration to the using statements. // container.LoadConfiguration();使用配置文件 // TODO: Register your type's mappings here. container.RegisterType<IArticleService, ArticleService>(new ContainerControlledLifetimeManager()); } } }
2、单例模式
上面我们添加了一行代码:container.RegisterType<IArticleService, ArticleService>(new ContainerControlledLifetimeManager());这句的作用是把IArticleService和ArticleService的映射注入容器,new ContainerControlledLifetimeManager()参数是通过lifetime管理,单例模式
如果不需要也可以使用:container.RegisterType<IArticleService, ArticleService>();即可
另外Unity还提供通过配置文件的方式进行:
<configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <containers> <container name="defaultContainer"> <register type="Practice.IocUnity.Service.Interface.IArticleService, Practice.IocUnity.Service.Interface" mapTo="Practice.IocUnity.Service.ArticleService, Practice.IocUnity.Service"/> <lifetime type="singleton" /> </container> </containers> </unity>