微软unity 注入mvc
首先获取开源unity ,引用,
新建UnityDependencyResolver 继承IDependencyResolver,代码如下:
public class UnityDependencyResolver : IDependencyResolver { IUnityContainer container; public UnityDependencyResolver(IUnityContainer container) { this.container = container; } public object GetService(Type serviceType) { try { return container.Resolve(serviceType); } catch (Exception) { return null; } } public IEnumerable<object> GetServices(Type serviceType) { return container.ResolveAll(serviceType); } }
写一个注册类
public class Bootstrapper { private static IUnityContainer container; /// <summary> /// 初始化IOC /// </summary> public static void Init() { //container = BuildUnityContainer(); container = new UnityContainer(); RegisterDependency(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); } /// <summary> /// 所有的注册 /// </summary> private static void RegisterDependency() { container.RegisterType<IDoctorTeamType, DoctorTeamType>(); } }
放到启动类 中执行Bootstrapper.Init();就可以了