我如何将Unity设置为依赖注入存储库到我的服务层
本文关键字:存储 我的 服务 注入 依赖 Unity 设置 | 更新日期: 2023-09-27 18:18:44
我已经设置了一个bootstrapper如下:
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<IService<Account>, AccountService>();
container.RegisterControllers();
return container;
}
我的控制器是这样的:
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)]);
}
然后尝试在引导程序中设置这些类型,如下所示:
container.RegisterType<IAzureTable<Account>, AzureTable<Account>(GetStorageAccount(), "TestAccounts")>();
container.RegisterType<IAzureTable<Product>, AzureTable<Product>(GetStorageAccount(), "TestProducts")>();
我想有什么我不明白,因为这产生了很多语法错误。我写错了吗?
是的,将这两个存储库视为构造函数参数,Unity将按照您的引导程序中指定的方式为您连接它们:
public class AccountService : BaseService, IService<Account>
{
public AccountService(StorageHelperType accountRepo, StorageHelperType productRepo) { base.Initialize();
_accountRepository = accountRepo;
_productRepository = productRepo;
}
在你的引导程序中,你应该能够指定它将从哪里使用InjectionConstructor获得这些参数(这里是一个很好的例子)(假设它们是不同的类型,如果它们是不同的类型,你可以把它们连接起来,Unity将它们分类)。
编辑新信息
当你用Unity注册你的泛型类型时,将它们包装在TypeOf语句中,因为这似乎是你如何绕过Unity泛型的方法
我在MVC3应用程序中使用Castle Windsor进行依赖注入,但我认为Unity的工作原理大致相同。我的依赖注入基于这篇博客文章。你可以看到他创建了自己的WindsorControllerFactory
,而不是使用默认的控制器工厂,后者会自动注入依赖项。
经过一些谷歌搜索,我确实找到了一些关于在MVC3中使用Unity的博客文章,像这个[1],这个[2]和这个[3],他们似乎都在创建一个UnityControllerFactory
了。所以我认为这就是你需要做的来实现自动构造函数注入