c# - 在 Unity 中注册类型时如何传入构造函数参数?

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

我在 Unity 中注册了以下类型:

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>();

AzureTable的定义和构造函数如下:

public class AzureTable<T> : AzureTableBase<T>, IInitializer where T : TableServiceEntity
{

    public AzureTable() : this(CloudConfiguration.GetStorageAccount()) { }
    public AzureTable(CloudStorageAccount account) : this(account, null) { }
    public AzureTable(CloudStorageAccount account, string tableName)
            : base(account, tableName) { }

我可以在 RegisterType 行中指定构造函数参数吗?例如,我需要能够传入 tableName。

这是我上一个问题的后续问题。我认为这个问题已经回答了,但我并没有真正清楚地询问如何获取构造函数参数。

最佳答案

这是一个 MSDN 页面,描述了您的需求,Injecting Values .看看使用 InjectionConstructor在您的寄存器类型行中上课。你最终会得到这样一行:

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(typeof(CloudStorageAccount)));

构造函数参数为InjectionConstructor是要传递给您的 AzureTable<Account> 的值.任何typeof参数留下统一来解析要使用的值。否则你可以通过你的实现:

CloudStorageAccount account = new CloudStorageAccount();
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(account));

或者命名参数:

container.RegisterType<CloudStorageAccount>("MyAccount");
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(new ResolvedParameter<CloudStorageAccount>("MyAccount")));

关于c# - 在 Unity 中注册类型时如何传入构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614936/

相关文章:

asp.net-mvc - 用于检索多级关系数据的 LINQ 查询

c# - 给定开始日期和结束日期的简单方法

c# - C#中指定 block 内的XmlDocument GetElementsByTagName

c# - GoogleOAuth2AuthenticationOptions google+ API 关闭

javascript - 在部分 View 中保留滚动事件

wpf - 卡特尔延迟加载包含 View / View 模型的装配体

.NET IoC - .NET Unity 的等效代码

unity-container - 统一处置对象

c# - StructureMap 对象重新加载

c# - 用于自动 INotifyPropertyChanged 实现的 Resharper 模板