gpt4 book ai didi

c# - Simple Injector 是否支持 MVC 4 ASP.NET Web API?

转载 作者:可可西里 更新时间:2023-11-01 02:59:08 25 4
gpt4 key购买 nike

我是 Simple Injector IOC 容器的新手。我将开始在一个需要使用 MVC 4 ASP.NET Web API 的 Multi-Tenancy ASP.NET MVC 实现的项目中工作。

我的问题是:Simple injector 是否支持 MVC 4 ASP.NET Web API?阅读简单的注入(inject)器文档,如 this引用了 MVC 3,我想知道是否也支持 MVC 4。

最佳答案

Does Simple injector IOC support MVC 4 ASP.NET Web API?

目前不支持MVC4 Web API, future 会支持。 The integration guide发生这种情况时会更新。


更新:Web API support已添加到 Simple Injector 2.5。


与此同时,您可以为简单注入(inject)器创建自己的 System.Web.Http.Dependencies.IDependencyResolver 实现。下面是在 IIS 托管环境中使用 Web API 的实现:

public class SimpleInjectorHttpDependencyResolver : 
System.Web.Http.Dependencies.IDependencyResolver
{
private readonly Container container;

public SimpleInjectorHttpDependencyResolver(
Container container)
{
this.container = container;
}

public System.Web.Http.Dependencies.IDependencyScope
BeginScope()
{
return this;
}

public object GetService(Type serviceType)
{
IServiceProvider provider = this.container;
return provider.GetService(serviceType);
}

public IEnumerable<object> GetServices(Type serviceType)
{
IServiceProvider provider = this.container;
Type collectionType = typeof(IEnumerable<>).MakeGenericType(serviceType);
var services =(IEnumerable<object>)this.ServiceProvider.GetService(collectionType);
return services ?? Enumerable.Empty<object>();
}

public void Dispose()
{
}
}

此实现不实现任何范围,因为您需要使用 Per Web Api Request在 Web 托管环境中实现范围界定的生命周期(请求可能在与其开始的线程不同的线程上结束)。

Because of the way Web API is designed , 显式注册所有 Web API Controller 非常重要。您可以使用以下代码执行此操作:

var services = GlobalConfiguration.Configuration.Services;
var controllerTypes = services.GetHttpControllerTypeResolver()
.GetControllerTypes(services.GetAssembliesResolver());

foreach (var controllerType in controllerTypes)
{
container.Register(controllerType);
}

您可以按如下方式注册 SimpleInjectorHttpDependencyResolver:

// NOTE: Do this as last step, after registering the controllers.
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorHttpDependencyResolver(container);

关于c# - Simple Injector 是否支持 MVC 4 ASP.NET Web API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11254292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com