您的位置:首页 > 其它

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

2014-06-05 23:15 495 查看
使用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()


结果显示:进攻阵型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: