標籤: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); }
MVC中 依賴注入(IOC)