c# - 如何将 Unity 设置为将依赖项注入(inject)存储库到我的服务层?

标签 c# asp.net-mvc asp.net-mvc-3 unity-container

我设置了一个 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/

相关文章:

razor - 在razor View 引擎中转义@字符

c# - 当用户在文本框中输入字符时通知 ViewModel

c# - 当方向改变时,如何防止 Xamarin Forms ScrollView 中的内容卡住?

c# - 将 Html.DropDownList 助手与 ViewBag 列表一起使用

javascript - 如何将字典从 Java Script Angular 客户端传递到 MVC3 服务器

asp.net-mvc-3 - MVC 3 DropDownList 重定向到 Diff 操作 OnChange?

java - 如何将 foreach c# 2d 数组循环转换为 java

c# - 如何在不添加无法访问的代码的情况下编译此异步 lambda?

c# - MVC3 绑定(bind)自定义集合

c# - 传递空的 SQL 参数给出错误