0

我有一個API控制器,它會觸發使用構造函數依賴注入的服務。我想用Windsor容器來注入這些依賴關係,但我不確定最佳實踐。從API控制器中的Castle Windsor容器中解析出來

這裏的API控制器工廠的一部分:

private readonly IWindsorContainer _container; 
private readonly ServiceFactory _serviceFactory; 
... 
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) 
{ 
    Arguments args = new Arguments(new { serviceFactory = _serviceFactory }); 
    IHttpController controller = (IHttpController)_container.Resolve(controllerType, args); 
    request.RegisterForDispose(new Release(() => _container.Release(controller))); 
    return controller; 
} 
... 

這裏的服務工廠的一部分:

private readonly IWindsorContainer _container; 
... 
public IService Create(Type serviceType, ApiRequestModel apiRequest) 
{ 
    Arguments args = new Arguments(new { request = apiRequest }); 
    return (IService)_container.Resolve(serviceType, args); 
} 
... 

這裏的API控制器的一部分:

private ServiceFactory _serviceFactory { get; set; } 
... 
public object Post([FromBody]ApiRequestModel request) 
{ 
    ... 
    Type serviceType = Assembly.Load("TestProject").GetType("TestClass"); 
    IService instance = _serviceFactory.Create(serviceType, request); 
    ... 
    _serviceFactory.Release(instance); 
} 
... 

服務工廠包含一個Windsor容器的實例,所以將它暴露給API控制是一個壞主意奧勒?如果是這樣,什麼是最好的選擇?謝謝。

回答

0

我的解決方案是使用一個通用的類型化的工廠設施(例如http://thesenilecoder.blogspot.com/2012/04/ioc-windsor-typedfactoryfacility-and.html

工廠只包括以下接口:

public interface IServiceFactory 
{ 
    T Create<T>(ApiRequestModel request) where T : IService; 

    void Release(IService service); 
} 

這裏是它如何被安裝到容器:

container.AddFacility<TypedFactoryFacility>(); 
container.Register(
    Component.For<IServiceFactory>().AsFactory(), 
    Classes.FromThisAssembly().BasedOn<IService>().LifestylePerWebRequest()); 

這被注入API控制器,並允許我創建泛型類型。在我去工廠之前,我使用了反射來解析泛型。

Type serviceType = Assembly.Load("TestProject").GetType("TestClass"); 
MethodInfo factoryMethod = _serviceFactory.GetType().GetMethod("Create").MakeGenericMethod(serviceType); 
IService instance = (IService)factoryMethod.Invoke(_serviceFactory, new object[] { request }); 
相關問題