我有一個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控制是一個壞主意奧勒?如果是這樣,什麼是最好的選擇?謝謝。