【发布时间】:2017-07-21 23:47:31
【问题描述】:
我有一个同时托管 WCF 和 Web API V2 ApiControllers 的 Web 项目。
两者都应该从使用 SimpleInjector 中受益。
这 2 种技术有 2 个不同的 nuget 包:
- SimpleInjector.integration.WebApi
- SimpleInjector.Ingegration.Wcf
在给定的情况下,两者的注册应该相同,解决此问题的最佳方法是什么? 我是否应该创建 2 个不同的容器,因为范围仅在请求打开时才有效?
我目前实现了以下,以使用正确的 ScopedLifestyles:
public static void ConfigureForWCF(Container container)
{
container.Options.DefaultScopedLifestyle = new WcfOperationLifestyle();
RegisterImplementations(container);
}
public static void ConfigureForWebAPI(Container container)
{
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
RegisterImplementations(container);
}
public static void RegisterImplementations(Container container)
{
// registrations for both WCF and Web API in here
container.Register<IMyInterface, MyClass>();
我知道这样称呼他们:
// container for WCF
var containerWCF = new Container();
SimpleInjectorConfiguration.ConfigureForWCF(containerWCF);
containerWCF.Verify();
// use the container for WCF
SimpleInjectorServiceHostFactory.SetContainer(containerWCF);
// container for Web API
var containerWebAPI = new Container();
SimpleInjectorConfiguration.ConfigureForWebAPI(containerWebAPI);
// this doesn't currently make sense for me as the controllers inheriting from ApiController get registered as Transient
//containerWebAPI.RegisterWebApiControllers(GlobalConfiguration.Configuration);
// instead I will register the Controllers manually
containerWebAPI.Verify();
// use the container for Web API
GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(containerWebAPI);
最终有可能使用同一个容器吗? (只要它们具有相同的注册,在两个容器上调用验证也没有意义)
【问题讨论】:
标签: c# wcf asp.net-web-api asp.net-web-api2 simple-injector