UnityDependencyResolver 的标准写法

public class UnityDependencyResolver : IDependencyResolver

{
    private readonly IUnityContainer _unityContainer;
 
    public UnityDependencyResolver(IUnityContainer unityContainer)
    {
        _unityContainer = unityContainer;
    }
 
    public object GetService(Type serviceType)
    {
        return (serviceType.IsClass && !serviceType.IsAbstract) ||
            _unityContainer.IsRegistered(serviceType) ?
            _unityContainer.Resolve(serviceType) : null;
    }
 
    public IEnumerable GetServices(Type serviceType)
    {
        return (serviceType.IsClass && !serviceType.IsAbstract) ||
            _unityContainer.IsRegistered(serviceType) ?
            _unityContainer.ResolveAll(serviceType) : new object[] {};
    }
}
 
Global.asax
protected void Application_Start()最后加入下面代码

IUnityContainer container = new UnityContainer();
container.RegisterType<IServiceA, ServiceA>();
container.RegisterType<IServiceB, ServiceB>();
container.RegisterType<IViewPageActivator, ViewPageActivator>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

MVC Controllerl里的定义(构造器函数注入实现)

public class HomeController : Controller
{
protected IServiceA _serviceA;
protected IServiceB _serviceB;

public HomeController(IServiceA serviceA, IServiceB serviceB)
{
_serviceA = serviceA;
_serviceB = serviceB;
}

public ActionResult Index()
{
ViewBag.A = _serviceA.Say();
ViewBag.B = _serviceB.Write();
return View();
}

}

05-27 11:50