4

回到 MVC3,我有一个自定义ControllerFactory,它将使用我自己的容器(由我的业务逻辑抽象)来实例化控制器并传递他们需要的服务。

我正在尝试使用新的ApiController.

我有一个静态/共享方法Core.DependencyResolverFactory.Resolver,它返回一个IDependencyResolver. 这又具有许多方法Resolve(...)ResolveAll(...)重载。

那么...我如何在 MVC4 中实现相同的功能?

Microsoft.Practices.ServiceLocation.IServiceLocator我尝试设置自己的 ServiceLocator,但在任何框架程序集中都找不到接口。

我不太担心被绑定到底层容器,因为它已经被 BL 抽象了,所以实际上我只需要一种快速而肮脏的方法来将我的类注入 MVC 的 DI。

有人可以指点我一个好的教程吗?

我现在所拥有的......

Sub Application_Start()
    ...Snip...

    'Suggested in the link on jrummel's answer...
    GlobalConfiguration.Configuration.DependencyResolver = New WebResolver
    'It fails due to DependencyResolver not being defined


    'I do have a 
    GlobalConfiguration.Configuration.ServiceResolver = New WebResolver
    'but it's read-only and it is of type System.Web.Http.Services.DependencyResolver not IDependencyResolver

End Sub

Private Class WebResolver
    Implements IDependencyResolver

    Private Resolver As Common.Interfaces.IDependencyResolver = Core.DependencyResolverFactory.QuickResolver

    Public Function GetService(serviceType As Type) As Object Implements IDependencyResolver.GetService
        Return Resolver.Resolve(serviceType)
    End Function

    Public Function GetServices(serviceType As Type) As IEnumerable(Of Object) Implements IDependencyResolver.GetServices
        Return Resolver.ResolveAll(serviceType)
    End Function
End Class
4

1 回答 1

3

ASP.NET Web API beta 自带IDependencyResolver,独立于 MVC。

asp.net上有一个教程:使用Web API Dependency Resolver

您可以从 NuGet 获取 ServiceLocator

于 2012-06-13T14:49:23.513 回答