.NET MVC - 在哪里使用依赖注入?

时间:2011-02-12 16:05:13

标签: asp.net-mvc dependency-injection

我目前正在使用IoC容器(Castle)将依赖项注入控制器。这是可能的,因为您需要创建一个启用依赖项注入的自定义控制器工厂。

依赖注入的其他例子是什么?在MVC应用程序中你会使用它,“工厂”在哪里发挥作用?

1 个答案:

答案 0 :(得分:3)

我正在使用Ninject。在我的项目中:

  • 服务层对象被注入控制器(使用构造函数)。
  • 将存储库注入服务层对象(使用构造函数)。
  • 将ObjectContext注入存储库(使用构造函数)。
  • web.config设置被封装到一个类中,该类实现IAppSettings接口,然后将其注入服务层。
  • NinjectActionInvoker作为IActionInvoker注入。它负责将服务注入ActionFilters。
  • 我有自己的IPrincipal接口实现,它被注入服务层,而不是引用HttpContext.Current.User

使用Ninject的示例:

public class UserService : GenericService<User>, IUserService
{
    public ISettingService SettingService { get; set; }
    public ICTEmailSender CTEmailSender { get; set; }
    public ICTSettings CTSettings { get; set; }
    public ICTPrincipal User { get; set; }
}

Ninject规则:

Bind<ICTPrincipal>().ToMethod(c => (ICTPrincipal)HttpContext.Current.User).OnlyIf(a => HttpContext.Current.User is ICTPrincipal);
Bind<ICTEmailSender>().To<CTEmailSender>();
Bind<ICTSettings>().To<CTSettings>();

不仅将服务注入控制器,还将部分服务注入其中。它使服务更容易测试。我相信它可以很容易地移植到Castle。