当前位置: 首页 > 工具软件 > StructureMap > 使用案例 >

MVC使用StructureMap实现依赖注入Dependency Injection

封烨伟
2023-12-01

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

 

结果显示:进攻阵型

转载于:https://www.cnblogs.com/darrenji/p/3771358.html

 类似资料: