現在、私はAsp.Net Web APIプロジェクトに依存関係を解決するためにSimple Injectorを使用しています。あなたがそのようにそれを設定することができますドキュメントからSimple InjectorとIHttpControllerActivatorを使用してASP.NET Web APIの依存関係を解決する
:ここ
protected void Application_Start() {
// Create the container as usual.
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
// Register your types, for instance using the scoped lifestyle:
container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
// Here your usual Web API configuration stuff.
}
主なポイントは、Web APIのコントローラを登録し、カスタム依存リゾルバを設定します。
しかし、私はちょうどAsp.NetのWeb APIの依存性注入を設定する方法のマーク・シーマンからこれらの記事を読んだ:これらの記事から
- Dependency Injection and Lifetime Management with ASP.NET Web API
- Dependency Injection in ASP.NET Web API with Castle Windsor
を、I IDependencyResolver
を実装してWeb APIの依存関係を解決するよりも良い選択肢があることを知りました。 この他のオプションは、IoCコンテナを介してアダプタとして機能するIHttpControllerActivator
の実装を作成することです。ここで
私はSimpleInjectorを使用してコード化されてきた実装です。このラインで
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
:
public class SimpleInjectorControllerActivator : IHttpControllerActivator
{
private readonly Container _container;
public SimpleInjectorControllerActivator(Container container)
{
_container = container;
}
public IHttpController Create(HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
request.RegisterForDispose(_container.BeginExecutionContextScope());
return (IHttpController)_container.GetInstance(controllerType);
}
}
とApplication_Start
方法で、私はこの行を置き換えました
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new SimpleInjectorControllerActivator(container));
IHttpControllerActivator
の実装がわかっていると思いますこのアプローチが有効で、正常なものと同じくらいうまくいくかどうかを確認します。
更新されたバージョンをポストするのではなく、SimpleInjectorControllerActivatorの簡略版で質問を更新しました。 – Steven