问题
I have the following type being registered in Unity:
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>();
The definition and constructors for AzureTable are as follows:
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) { }
Can I specify the constructor arguments in the RegisterType line? I need to be able to pass in the tableName for example.
This is a follow-up to my last question. That question was I think answered but I didn't really clearly ask how to get the constructor arguments in.
回答1:
Here is an MSDN page describing what you require, Injecting Values. Take a look at using the InjectionConstructor class in your register type line. You will end up with a line like this:
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(typeof(CloudStorageAccount)));
The constructor parameters to InjectionConstructor are the values to be passed to your AzureTable<Account>. Any typeof parameters leave unity to resolve the value to use. Otherwise you can just pass your implementation:
CloudStorageAccount account = new CloudStorageAccount();
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(account));
Or a named parameter:
container.RegisterType<CloudStorageAccount>("MyAccount");
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(new ResolvedParameter<CloudStorageAccount>("MyAccount")));
回答2:
You could give this a try:
// Register your type:
container.RegisterType<typeof(IAzureTable<Account>), typeof(AzureTable<Account>)>()
// Then you can configure the constructor injection (also works for properties):
container.Configure<InjectedMembers>()
.ConfigureInjectionFor<typeof(AzureTable<Account>>(
new InjectionConstructor(myConstructorParam1, "my constructor parameter 2") // etc.
);
More info from MSDN here.
来源:https://stackoverflow.com/questions/8614936/how-can-i-pass-in-constructor-arguments-when-i-register-a-type-in-unity