在mvc中使用Unity
一、在Nuget管理器中下载“Unity“
二、在根目录的App_Start文件夹中添加三个cs文件
创建UnityConfig.cs
//添加两个命名空间
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
//这是代码块
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
#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>();
}
}
创建UnityDependencyResolver.cs
using System.Web.Mvc;
/// <summary>
/// 使用unity必须实现的两个接口之一
/// 它的作用我也不知道
/// </summary>
public class UnityDependencyResolver : IDependencyResolver
{
IUnityContainer container;
public UnityDependencyResolver(IUnityContainer container)
{
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
添加UnityWebActivator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(WebApp.App_Start.UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(WebApp.App_Start.UnityWebActivator), "Shutdown")]
namespace 你的命名空间
{
public class UnityWebActivator
{
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
- 三、根目录的Global.asax中注册一下
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//这是unity,上面四行不要去动。
IUnityContainer container = GetUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
/// <summary>
/// 这是unity的注册
/// </summary>
/// <returns></returns>
private IUnityContainer GetUnityContainer()
{
IUnityContainer container = new UnityContainer()
.RegisterType<IControllerActivator, CustomControllerActivator>();
//配置了多少就写多少
//container.LoadConfiguration("container name的值")
container.LoadConfiguration("UnityStudentServceBLL");
//container.LoadConfiguration("UnityPayServiceBLL");
//container.LoadConfiguration("UnityTeacherServiceBLL");
//container.LoadConfiguration("UnityGradesServiceBLL");
return container;
}
}
- 四、修改配置文件
在根目录中找到Web.config,修改配置信息
<!--这个configSections节点必须是第一个否则会出错-->
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity>
<containers>
<!--container可以有多个-->
<container name="随便起">
<register type="命名空间.接口文件名(不要扩展名), 程序集(一般和命名空间一样)" mapTo="命名空间.实现接口的类的名称(不要扩展名), 程序集(一般和命名空间一样)" />
</container>
<!--比如这样-->
<container name="UnityStudentServceBLL">
<register type="MySchool.IBLL.IStudentService, MySchool.IBLL" mapTo="MySchool.BLL.StudentService, MySchool.BLL" />
</container>
</containers>
</unity>
- 五、使用
public class BaseController : Controller
{
[Dependency]
public IStudentService StudentService { get; set; }
//[Dependency]
//public 配置文件中注册过的接口 起个牛13名 { get; set; }
//
//
}
- 六、结束
搞完之后两个类就可以解耦了,不需要对业务类new来new去了。