MVC使用StructureMap实现依赖注入Dependency Injection
2014-06-05 23:15
495 查看
使用StructureMap也可以实现在MVC中的依赖注入,为此,我们不仅要使用StructureMap注册各种接口及其实现,还需要自定义控制器工厂,借助StructureMap来生成controller实例。
有这样的一个接口:
2个接口实现:
借助StructureMap(通过NuGet安装)自定义控制器工厂:
在全局中注册控制器工厂以及注册接口和默认实现:
ObjectFactory.Initialize(cfg => cfg.For<IStrategy>().Use<AttackStrategy>());
ControllerBuilder.Current.SetControllerFactory(new StrategyControllerFactory());
HomeController中:
Home/Index.cshtml中:
结果显示:进攻阵型
有这样的一个接口:
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()
结果显示:进攻阵型
相关文章推荐
- 扩展ASP.NET MVC三层框架并使用StructureMap实现依赖注入1
- 扩展ASP.NET MVC三层框架且使用StructureMap实现依赖注入1-Model层
- 扩展ASP.NET MVC三层框架并使用StructureMap实现依赖注入2
- 扩展ASP.NET MVC三层框架并使用StructureMap实现依赖注入2-Repository层的实现
- 扩展ASP.NET MVC三层框架并使用StructureMap实现依赖注入1-Model层的实现
- 扩展ASP.NET MVC三层框架且使用StructureMap实现依赖注入1-Model层
- [ASP.NET MVC 小牛之路]05 - 使用 Ninject实现依赖注入
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
- .NET中使用Unity和StructureMap来实现依赖注入Dependency Injection
- Asp.Net Mvc使用Autofac实现依赖注入
- Asp.net MVC 中使用 Ninject 实现依赖注入
- 在MVC中使用泛型仓储模式和依赖注入实现增删查改
- Asp.mvc(三) ~ 使用 Autofac 实现依赖注入
- 使用Autofac在ASP.NET Web API上实现依赖注入
- MVC3使用Unity实现依赖注入接口与于实现类自动注册
- 使用Autofac在ASP.NET Web API上实现依赖注入
- seasar2中使用ognl实现依赖注入
- NopCommerce是如何使用Autofac实现依赖注入的
- 【翻译】Deft JS:通过依赖注入实现低耦合MVC
- 【翻译】Deft JS:通过依赖注入实现低耦合MVC