最近公司用到了Unity,自己就研究了一下。
新建一个ASP.NET MVC基本项目,在NuGet上引入Unity4.0.1最新版。
因为我使用的项目为ASP.NET MVC,所以又添加一个Unity bootstrapper for ASP.NET MVC。
NuGet会帮你在App_Start文件夹下自动添加两个文件UnityConfig.cs和UnityMvcActivator.cs。
文件UnityConfig.cs是配置Unity依赖注入用的,可以分为两种
这两种方式的不同点在于,修改依赖注入时,如果是方式一可以在系统运行时修改(支持热插拔)。
文件UnityWebActivator.cs是我们创建的依赖关系注册到MVC中。
我们需要做的是在Global.asax文件中将Unity运行。
下面来详细讲述一下这两方式的配置:
方式一使用web.config配置:
1.在UnityConfig.cs下将注释取消container.LoadConfiguration()
/// <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>(); }
2.在configSections节点下添加以下内容
<configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/> </configSections>
3.配置unity节点信息
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <assembly name="IBLL"/> <assembly name="BLL"/> <containers> <container> <register type="IBLL.ITest,IBLL" mapTo="BLL.Test,BLL" /> </container> </containers> </unity>
配置完成运行就ok了。
这是我遇到一个问题,找了很多资料才解决的
原来web.config是这样配置的
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <containers> <container> <register type="IBLL.ITest" mapTo="BLL.Test" /> </container> </containers> </unity>
这种情况下会报这种错误
The type name or alias IBLL.ITest could not be resolved. Please check your configuration file and verify this type name.
这里找到了答案http://stackoverflow.com/questions/14935645/type-name-could-not-be-resolved-please-check-config-file
方式二使用代码配置:
这种方式十分的简单基本上我们只要参考作者给的提示就ok
在UnityConfig.cs下配置如下代码:
/// <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<IBLL.ITest,BLL.Test>(); }
以上是个人使用经验分享给大家,上面的内容比较浅显,如果有错误请大家指正