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

    }

  • 相关阅读:
    Anaconda3的Jupyter notebook调用ArcGISPro的Arcpy
    ArcMap 创建空间邻接矩阵
    Anaconda3的Jupyter notebook切换Python3和Python2环境并调用Arcpy
    PHP.MVC的模板标签系统(二)
    PHP汉字转拼音的类
    Linux 解压命令大全
    ASP应用之模板采用
    PHP中的串行化变量和序列化对象(一)
    CSS常用技巧介绍
    ASP实现多图片上传(一)
  • 原文地址:https://www.cnblogs.com/sjqq/p/7554616.html
Copyright © 2020-2023  润新知