【发布时间】:2015-03-09 17:03:42
【问题描述】:
我正在尝试使用 Castle Windsor 实施 DI。目前我有一个像这样重载构造函数的控制器(这是这里描述的反模式:https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=97):
public class MyController : ApiController
{
protected IStorageService StorageService;
protected MyController()
{
StorageService = StorageServiceFactory.CreateStorageService(User.Identity as ClaimsIdentity);
}
protected MyController(IStorageService storageService)
{
StorageService = storageService;
}
}
我正在尝试摆脱第一个构造函数,让 Castle Windsor 处理存储服务依赖项的解析。
我像这样创建了一个 Castle Windsor 安装程序类:
public class StorageServiceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<IStorageService>()
.UsingFactoryMethod(
() => StorageServiceFactory.CreateStorageService(User.Identity as ClaimsIdentity)));
}
}
问题在于User(类型为IPrincipal)是ApiController 上的一个属性,因此安装程序无法访问它。我怎样才能做到这一点?
更新:
@PatrickQuirk 似乎暗示有更好的方法可以使用 Castle Windsor 做到这一点,而根本不需要工厂。
我的 StorageServiceFactory 如下所示:
public static class StorageServiceFactory
{
public static IStorageService CreateStorageService(ClaimsIdentity identity)
{
if (identity == null)
{
return null;
}
Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
if (providerKeyClaim == null || string.IsNullOrEmpty(providerKeyClaim.Value))
{
return null;
}
StorageProviderType storageProviderType;
string storageProviderString = identity.FindFirstValue("storage_provider");
if (string.IsNullOrWhiteSpace(storageProviderString) || !Enum.TryParse(storageProviderString, out storageProviderType))
{
return null;
}
string accessToken = identity.FindFirstValue("access_token");
if (string.IsNullOrWhiteSpace(accessToken))
{
return null;
}
switch (storageProviderType)
{
// Return IStorageService implementation based on the type...
}
}
}
有没有办法将选择正确的IStorageService 合并到 Windsor 的依赖解析中并完全避免使用工厂?还是我还需要它?
我喜欢@PatrickQuirk 的解决方案,只是为了依赖注入而必须为工厂创建包装器和相应的包装器接口似乎很奇怪。理想情况下,我会让 api 控制器的构造函数接受 IStorageService 作为参数,这似乎更直观/与实际需要设置的字段一致。
【问题讨论】:
标签: asp.net-web-api dependency-injection inversion-of-control castle-windsor ioc-container