MVC 4和Unity,向WebAPI控制器注入依赖项 [英] MVC 4 and Unity, injecting dependencies to WebAPI controllers

查看:219
本文介绍了MVC 4和Unity,向WebAPI控制器注入依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,

我是MVC的新手,但我陷入了一个问题.我设法找到的所有示例都引用了简单的控制器,而不是API控制器.也许任何人都有一个有效的代码示例,该示例说明如何在Application_Start()上将依赖项注册到Unity并对其进行调整,以便一旦创建了apicontroller类,就将正确的依赖项传递给了它.假设这是我的控制器的定义:

Dear all,

I''m new to MVC and I got stuck on a problem. All the examples I managed to find refer to simple controllers and not to API controllers. Perhaps any one has a working code example on how to, on Application_Start(), register the dependencies to Unity and tweak the code so that once my apicontroller class is created, the right dependency is passed to it. Let''s say that this is the definition of my controller:

public class BookController : ApiController
{
    private IBookService bookSerivce;

    public BookController (IBookService bookSerivce)
    {
        this.bookSerivce= bookSerivce;
    }
}



我希望通过以下方式统一注册:



And I expect to register it in unity in the following way:

UnityContainer container = new UnityContainer();

// Register services
container.RegisterType<IBookService , BookService>();

// Register controllers
container.RegisterType<IHttpController, BookController>("Books");



现在,为了使MVC统一使用以解决依赖关系,开始创建此控制器的实例并将依赖关系传递给它,我需要做些什么?

我正在使用MVC4.任何想法将不胜感激.

干杯



Now, what do I need to do in order to make MVC use unity for resolving the dependencies, start creating instances of this controller and passing the dependencies to it?

I''m using MVC 4. Any idea will be appreciated.

Cheers

推荐答案

我发现Seemann在DI和WebAPI上的帖子:
http://blog.ploeh.dk/2012/10/03/DependencyInjectionInASPNETWebAPIWithCastleWindsor.aspx [ ^ ]

一旦适应使用Unity而不是CW,我就使它起作用.

这是我的实现:

I found Seemann''s post on DI and WebAPI:
http://blog.ploeh.dk/2012/10/03/DependencyInjectionInASPNETWebAPIWithCastleWindsor.aspx[^]

Once adapted to use Unity instead of CW, I made it work.

This is my implementation:

public class UnityCompositionRoot : IHttpControllerActivator
{
    private readonly IUnityContainer container;

    public UnityCompositionRoot(IUnityContainer container)
    {
        this.container = container;
    }

    public IHttpController Create(HttpRequestMessage request, 
        HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        var controller = (IHttpController)this.container.Resolve(controllerType);
        return controller;
    }
}



然后在Application_Start()的Global.asax中,执行以下操作:



Then in Global.asax in Application_Start() I did the following:

UnityContainer container = new UnityContainer();
container.RegisterType<IBookService, BookService>();

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), 
    new UnityCompositionRoot(container));



希望对您有所帮助.

干杯



Hope it helps.

Cheers


这篇关于MVC 4和Unity,向WebAPI控制器注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆