标签:style blog color io os ar for 文件 sp
1)Unity 配置文件
<?xml version="1.0" encoding="utf-8"?> <unity> <typeAliases> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity"/> <!--action的构造函数需要接口定义,依赖注入需要接口--> <typeAlias alias="IFoo" type="MyTest.BizInterfaces.IFoo,MyTest.BizInterfaces"/> </typeAliases> <containers> <container name="containerOne"> <types> <!--action的构造函数需要接口定义,依赖注入需要接口--> <type type="IFoo" mapTo="MyTest.Business.Foo, MyTest.Business"/> </types> </container> </containers> </unity>
2)UnityConfigurator
namespace MyTest.Common.IOC { public class UnityConfigurator { public static IUnityContainer CreateContainer() { IUnityContainer parentContainer = new UnityContainer(); IUnityContainer childContainer = parentContainer.CreateChildContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(childContainer, "containerOne"); return childContainer; } } }
3)UnityControllerFactory
namespace MyTest.Common.IOC { public class UnityControllerFactory : DefaultControllerFactory { readonly IUnityContainer container; public UnityControllerFactory(IUnityContainer container) { this.container = container; var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where typeof(IController).IsAssignableFrom(t) select t; foreach (var t in controllerTypes) { #if DEBUG System.Diagnostics.Debug.WriteLine("RegisterType: " + t.Name); #endif container.RegisterType(t); } } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) return null; return (IController)container.Resolve(controllerType); } } }
4) Under Register Routes
public static void RegisterRoutes(RouteCollection routes) { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); Infratructure.RouteConfigurator.RegisterRoutes(RouteTable.Routes); IUnityContainer container = UnityConfigurator.CreateContainer(); UnityControllerFactory factory = new UnityControllerFactory(container); ControllerBuilder.Current.SetControllerFactory(factory); }
标签:style blog color io os ar for 文件 sp
原文地址:http://www.cnblogs.com/kaleidoscope/p/4026412.html