2014-04-09 2 views
1

필자는 필자가 필요로하는보다 복잡한 몇 가지 예제를 읽었으며 간단하고 간결한 패턴으로이 문제를 해결하는 데 어려움을 겪고 있습니다.AutoFac으로 매개 변수를 받아들이는 공장 주입하기

인터페이스 이름이 ICustomService이고 ICustomService가 여러 개 구현되어 있다고 가정 해 보겠습니다. 또한 런타임에 ICustomService가 매개 변수를 기반으로 사용할 것인지를 결정해야하는 클래스 Consumer가 있습니다. 다음과 같이

그래서 나는 클래스를 생성 :

public class Consumer 
{ 
    private CustomServiceFactory customServiceFactory; 

    public Consumer(CustomServiceFactory _customServiceFactory) 
    { 
     customServiceFactory = _customServiceFactory; 
    } 

    public void Execute(string parameter) 
    { 
     ICustomService Service = customServiceFactory.GetService(parameter); 
     Service.DoSomething(); 
    } 
} 

public class CustomServiceFactory 
{ 
    private IComponentContext context; 
    public CustomServiceFactory(IComponentContext _context) 
    { 
     context = _context; 
    } 

    public ICustomService GetService(string p) 
    { 
     return context.Resolve<ICustomService>(p); // not correct 
    } 
} 

public class ServiceA : ICustomService 
{ 
    public void DoSomething() 
    { 

    } 
} 

public class ServiceB : ICustomService 
{ 
    public void DoSomething() 
    { 

    } 
} 

장점 내 공장 인터페이스를 구현하는 데 있나요? Consumer.Execute ("A")가 WorkerA 및 Consumer.Execute ("B")에서 DoSomething을 호출하도록 Workf에서 DoSomething을 호출하도록 공장을 수정하고 Autofac에 이러한 클래스를 등록하려면 어떻게해야합니까?

답변

1

당신은 키 ICustomService 당신의 구현을 등록 할 것입니다 감사합니다. 예를 들어 :

builder.RegisterType<FooService>.Keyed<ICustomService>("someKey"); 
builder.RegisterType<BarService>.Keyed<ICustomService>("anotherKey"); 

하고 그런 다음 팩토리 메소드는 다음과 같습니다 당신이 한 단계 더이 걸릴 분리 할 수 ​​

public ICustomService GetService(string p) 
{ 
    return context.ResolveKeyed<ICustomService>(p); 
} 

을하지만 CustomServiceFactoryIComponentContext에서 :

public class CustomServiceFactory 
{ 
    private Func<string, ICustomService> _create; 

    public CustomServiceFactory(Func<string, ICustomService> create) 
    { 
     _create = create; 
    } 

    public ICustomService GetService(string p) 
    { 
     return _create(p); 
    } 
} 

하는 당신이 것 이렇게 등록 :

builder.Register(c => { 
    var ctx = c.Resolve<IComponentContext>(); 
    return new CustomServiceFactory(key => ctx.ResolveKeyed<ICustomService>(key)); 
}); 

그리고이 시점에서 CustomServiceFactory에 질문에 대해 생략 된 다른 동작이 없다고 가정하면 Func<string, ICustomService>을 직접 사용하고 등록 할 수 있습니다.

+0

고맙습니다! 나는 Func 를 직접 등록하는 방법을 제외하고는 모든 것을 이해합니다. 그리고 나는 그것을 해결할 수 있다고 확신합니다. –

관련 문제