Mvc .Net Coreに付属する依存性注入フレームワークを活用しています。サービスクラスの同じインスタンスを使用したいが、そのクラスが実装する2つの異なるインターフェイスを使用する場合があります。私はAddScopeを使用してクラスとインターフェイスを結び付けています。私の場合、AddSingletonを使用してStartupクラス内でMyServiceClassを直接インスタンス化することはできません。MVC .Net Coreの依存性注入フレームワークで非常に同じオブジェクトインスタンスを活用する方法
次のコードサンプルは私のシナリオを示しています。 MyOtherClassのコンストラクタがMyServiceClassの同じインスタンスを両方のパラメータで受け取るようにするにはどうすればよいかということです。
using System;
namespace TestNamespace {
public interface Interface1 { void DoThisThing(); }
public interface Interface2 { void DoThatThing(); }
public class MyServiceClass : Interface1, Interface2
{
public MyServiceClass()
{
}
public void DoThisThing()
{
Console.Write("Keep thinking differently. (Steve Jobs)");
}
public void DoThatThing()
{
Console.Write("Keep calm and carry on.");
}
}
public class MyOtherClass
{
private Interface1 _service1;
private Interface2 _service2;
public MyOtherClass(Interface1 service1, Interface2 service2)
{
_service1 = service1;
_service2 = service2;
}
public void DoAllThingsTogether()
{
_service1.DoThisThing();
_service2.DoThatThing();
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddScoped<Interface1, MyServiceClass>();
services.AddScoped<Interface2, MyServiceClass>();
services.AddMvc();
}
} }
あなたが代わりに '' AddScoped'のAddInstance'を使用することはできますか?他のオプションは、注入する特定のインスタンスの作成と検査を担当する実際のクラスではなく、ファクトリを登録することです。 – Hintham
AddInstanceは、.Net Coreの最近のアップデート(1.0.1)では利用できません。 – Arash