c# – .NET MVC依赖注入模型?

栏目: ASP.NET · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/6461601/net-mvc-dependency-injection-on-models

问题:有没有办法使用Ninject将依赖项注入我的MVC模型?

首先,我是MVC和DI(和stackoverflow,btw)的新手,所以我想确保我正在走这个问题的正确路径.我一直在搜索几天的答案,但我找不到一个干净的解释…我正在使用C#,.NET4,MVC3,Ninject和VS2010.

这是场景:我有一个新的用户表单,用户可以设置其登录,角色和设置其他配置文件数据.提交后,我需要将登录信息保存到MembershipProvider,RoleProvider等角色…它有点毛茸茸,因为我根据我的项目要求使用双提供程序(Active Directory /本地数据库)因此,如果用户已经存在,如果允许自定义任何角色等等,则确定哪个提供者要保存的逻辑有一点.

我觉得这个逻辑应该在我的模型上的.Save()方法中.然而,我需要将我的提供程序的实例注入到我的模型中,而Ninject似乎不会注入模型(至少不使用NuGet软件包附带的默认设置).所以我的初步问题.

我可以想到一些替代品

>也许模型是这个逻辑开始的不好的地方,我应该将逻辑抽象成一个服务?但是为了这个保存功能而提供服务似乎对我来说太过分了.

>我可以在控制器中吃饱胀,但是我被告知“胖”控制器是一个不好的做法.

>我想我可以将我的提供者注入我的控制器,然后将这些依赖关系传递给我的模型,但是这似乎有点不合.

所以…有没有办法Ninject的模型,或者我需要重新因素,因为我是一个新手吗?

我会选择一个.这不是过度的 – 添加一个类和一个接口只是几行代码,它保持你的实现整洁,也许以后你会想添加更多的方法…更新一个用户?

添加一个接口和类来处理你的控制器使用的–ninject将为你获取这个实例.我以IMembershipAndRoleService为例.

public interface IMembershipAndRoleService
{
    void ProcessNewUser(User newUser);
}

public class YourController : Controller
{
    private readonly IMembershipAndRoleService _membershipAndRoleService;

    public YourController(IMembershipAndRoleService membershipAndRoleService)
    {
        _membershipAndRoleService = membershipAndRoleService;
    }

    [HttpPost]
    public ActionResult NewUserFormAction(NewUserForm newUserForm)
    {
        //process posted form, possibly map / convert it to User then call to save
        _membershipAndRoleService.ProcessNewUser(user);
        //redirect or return view
    }
}

最后,实现IMembershipAndRoleService的类,该类将使用您的成员资格和角色提供者或其他接口,使您的逻辑简化.

http://stackoverflow.com/questions/6461601/net-mvc-dependency-injection-on-models


以上所述就是小编给大家介绍的《c# – .NET MVC依赖注入模型?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

About Face 2.0

About Face 2.0

Alan Cooper、Robert M. Reimann / Wiley / March 17, 2003 / USD 35.00

First published seven years ago-just before the World Wide Web exploded into dominance in the software world-About Face rapidly became a bestseller. While the ideas and principles in the original book......一起来看看 《About Face 2.0》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具