使用Global.asax进行依赖注入

时间:2014-08-28 06:14:32

标签: asp.net-mvc dependency-injection unity-container

我正在使用依赖注入注入接口和类

我在Global.asax中使用它

  new UnityContainer().RegisterType<IBookingService, BookingService>()

和控制器

IBookingService bookingService

现在我想改变控制器级别接口的注入实现类

如何使用控制器级别进行操作?

我想在控制器级别做一些像这样的事情

private readonly IBookingService bookingService;

if(countryCode = SE ){

bookingService = new bookingSE();

}

else IF (countryCode = NO ){

bookingService = new bookingNO();

}

我想对此

使用依赖注入

2 个答案:

答案 0 :(得分:1)

确保使用Unity.Mvc NuGet package。这会将App_Start\UnityConfig.cs文件添加到您的项目中,您可以在其RegisterTypes方法中添加注册,如下所示:

container.RegisterType<IBookingService, BookingService>();

也许您已经这样做了,但我想确保您使用new UnityContainer().RegisterType的确切代码示例无效。

此包的另一个有趣的事情可以在App_Start\UnityWebActivator.cs文件中查看:

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

该行将Unity容器注册为标准MVC DependencyResolver。这允许将构造函数注入应用于控制器。有了这个,您可以按如下方式定义控制器:

public class MyCoolController : Controller
{
    private readonly IBookingService bookingService;

    public MyCoolController(IBookingService bookingService)
    {
        this.bookingService = bookingService
    }

    public ActionResult Index()
    {
        // your usual MVC stuff here.
    }
}

在几乎所有情况下,建议使用构造函数注射所有形式的注射,因此坚持使用构造函数注射,除非没有其他方法。如果您认为没有别的办法,请在Stackoverflow上询问。我们或许可以就您的代码和设计提供一些反馈。

答案 1 :(得分:0)

只需致电Resolve

var bookingService= container.Resolve<IBookingService>()