-1
我正在嘗試使用Autofac KeyFilter實現解析實例。如果使用ResolveKeyed <>顯式解析實例,我會得到結果。然而,當在構造函數中使用KeyFilter時,我看到不同的實例被解析爲參數。Key Filter構造函數用法Autofac問題
這裏是個小例子..我想出了..
public enum TestApiEnum
{
TestA,
TestB
}
public interface ITestService
{
}
public interface ITestApi
{
}
public class TestService : ITestService
{
public TestService([KeyFilter(TestApiEnum.TestA)]ITestApi testApiA,
[KeyFilter(TestApiEnum.TestB)] ITestApi testApiB)
{
}
}
public class TestApiA : ITestApi
{
public TestApiA(TestApiEnum testEnum)
{
TestApiEnum = testEnum;
}
public TestApiEnum TestApiEnum { get; set; }
}
public class TestApiB: ITestApi
{
public TestApiB(TestApiEnum testEnum)
{
TestApiEnum = testEnum;
}
public TestApiEnum TestApiEnum { get; set; }
}
生成器註冊
builder.RegisterType<TestService>()
.As<ITestService>();
builder.RegisterType<TestApiA>()
.AsImplementedInterfaces()
.Keyed<ITestApi>(TestApiEnum.TestA)
.WithAttributeFiltering()
.WithParameter("testEnum", TestApiEnum.TestA);
builder.RegisterType<TestApiB>()
.AsImplementedInterfaces()
.Keyed<ITestApi>(TestApiEnum.TestB)
.WithAttributeFiltering()
.WithParameter("testEnum", TestApiEnum.TestB);
var builder = AutofacConfig.ConfigureContainer();
using (var scope = builder.BeginLifetimeScope())
{
// Able to Resolve following two..
var testApiA = scope.ResolveKeyed<ITestApi>(TestApiEnum.TestA);
var testApiB = scope.ResolveKeyed<ITestApi>(TestApiEnum.TestB);
// following test service resolves both parameters as **testApiB** and **testApiB**
var testservice = scope.Resolve<ITestService>();
}