zoukankan      html  css  js  c++  java
  • MVC Controller构造器注入

    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();
    }

    }

  • 相关阅读:
    pat甲级1004 Counting Leaves
    pat甲级1003 Emergency
    pat甲级1002 A+B for Polynomials
    pat甲级1001 A+B Format
    【转载】sql注入之入门
    JavaScript基础学习笔记
    django 安装
    python web编程CGI
    python urllib库
    python数据库编程
  • 原文地址:https://www.cnblogs.com/sjqq/p/7554616.html
Copyright © 2011-2022 走看看