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

    结果显示:进攻阵型

  • 相关阅读:
    js array数组检测方式
    js 获取时间戳
    接收二进制流(ArrayBuffer) ,并且显示二进制流图片
    文字小于12px时,设置line-height不居中问题
    设置文字小于12px
    Kafuka面试(整合Kafka两种模式区别)
    secondary namenode 检查点
    MapReduce总结
    Map、Reduce和Job方法总结
    Hadoop 两种环境下的checkpoint机制
  • 原文地址:https://www.cnblogs.com/darrenji/p/3771358.html
Copyright © 2011-2022 走看看