我设置了一个 Bootstrap ,如下所示:
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<IService<Account>, AccountService>();
container.RegisterControllers();
return container;
}
我的 Controller 如下所示:
public AccountsController(IService<Account> accountService) {
_account = accountService;
}
调用时,它会从 accountService 中正确设置 _account,如下所示:
public class AccountService : BaseService, IService<Account>
{
public AccountService() { base.Initialize();
_accountRepository = StorageHelper.GetTable<Account>();
_productRepository = StorageHelper.GetTable<Product>();
}
您可以在此处看到 AccountService 依赖于设置两个存储库。在 Unity 中,有什么方法可以让我指定这种依赖关系,这样我就不必在 StorageHelper.GetTable(); 中编写代码了。
更新:
我根据以下建议添加了以下代码:
public AccountService(
IAzureTable<Account> accountRepository,
IAzureTable<Product> productRepository) {
//base.Initialize();
_accountRepository = accountRepository;
_productRepository = productRepository;
}
原始代码如下:
public static IAzureTable<T> GetTable<T>() where T : TableServiceEntity
{
return new AzureTable<T>(GetStorageAccount(), TableNames[typeof(T)]);
}
然后尝试在 Bootstrap 中设置这些类型,如下所示:
container.RegisterType<IAzureTable<Account>, AzureTable<Account>(GetStorageAccount(), "TestAccounts")>();
container.RegisterType<IAzureTable<Product>, AzureTable<Product>(GetStorageAccount(), "TestProducts")>();
我想有些东西我不明白,因为这产生了很多语法错误。我这里做错了吗?
最佳答案
是的,将这两个存储库视为构造函数参数,Unity 将按照 Bootstrap 中的指定将它们连接起来:
public class AccountService : BaseService, IService<Account>
{
public AccountService(StorageHelperType accountRepo, StorageHelperType productRepo) { base.Initialize();
_accountRepository = accountRepo;
_productRepository = productRepo;
}
在你的 Bootstrap 中,你应该能够指定使用 InjectionConstructor 获取这些参数的确切位置(一个很好的例子 here )(假设它们是不同的类型,如果它们是不同的类型,你可以将它们连接起来并Unity 会将它们整理出来)。
编辑新信息
当您使用 Unity 注册泛型类型时,请将它们包装在 TypeOf 语句中,因为这似乎是您使用 Unity 绕过泛型的方式(来源: MSDN )
关于c# - 如何将 Unity 设置为将依赖项注入(inject)存储库到我的服务层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614113/