zoukankan      html  css  js  c++  java
  • MVC使用StructureMap实现依赖注入Dependency Injection

    使用StructureMap也可以实现在MVC中的依赖注入,为此,我们不仅要使用StructureMap注册各种接口及其实现,还需要自定义控制器工厂,借助StructureMap来生成controller实例。

    有这样的一个接口:

    namespace MvcApplication1
    {
        public interface IStrategy
        {
            string GetStrategy();
        }
    }

    2个接口实现:

    namespace MvcApplication1
    {
        public class AttackStrategy : IStrategy
        {
            public string GetStrategy()
            {
                return "进攻阵型";
            }
        }
    }
    
    和
    
    namespace MvcApplication1
    {
        public class DefenceStrategy : IStrategy
        {
            public string GetStrategy()
            {
                return "防守阵型";
            }
        }
    }

    借助StructureMap(通过NuGet安装)自定义控制器工厂:

    using System.Web;
    using System.Web.Mvc;
    using StructureMap;
    
    namespace MvcApplication1
    {
        public class StrategyControllerFactory : DefaultControllerFactory
        {
            protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, System.Type controllerType)
            {
                if (controllerType == null)
                {
                    throw new HttpException(404, "没有找到相关控制器");
                }
                return ObjectFactory.GetInstance(controllerType) as IController;
            }
        }
    }

    在全局中注册控制器工厂以及注册接口和默认实现:

    ObjectFactory.Initialize(cfg => cfg.For<IStrategy>().Use<AttackStrategy>());
    ControllerBuilder.Current.SetControllerFactory(new StrategyControllerFactory());

    HomeController中:

    using System.Web.Mvc;
    
    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            private IStrategy _strategy;
    
            public HomeController(IStrategy strategy)
            {
                this._strategy = strategy;
            }
    
            public ActionResult Index()
            {
                ViewData["s"] = _strategy.GetStrategy();
                return View();
            }
    
        }
    }

    Home/Index.cshtml中:

    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Index</h2>
    
    @ViewData["s"].ToString()

    结果显示:进攻阵型

  • 相关阅读:
    集合set
    字典
    元组
    列表
    for循环
    Windows调试2.异常产生详细流程
    双机环境搭建
    Windows调试1.WinDbg基本使用-异常基础知识
    PE基础7-HOOK练习
    PE基础6_远程线程注入-HOOK(消息-InLine-IAT)
  • 原文地址:https://www.cnblogs.com/darrenji/p/3771358.html
Copyright © 2011-2022 走看看