在Unity中注册类型时如何传递构造函数参数? [英] How can I pass in constructor arguments when I register a type in Unity?

查看:181
本文介绍了在Unity中注册类型时如何传递构造函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following type being registered in Unity:

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

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

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) { }

我可以在RegisterType行中指定构造函数参数吗?例如,我需要能够传递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.

推荐答案

以下是MSDN页面,其中描述了您的要求,

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)));

InjectionConstructor的构造函数参数是要传递给AzureTable<Account>的值.任何typeof参数都保持统一以解析要使用的值.否则,您可以通过实施:

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));

或命名参数:

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

这篇关于在Unity中注册类型时如何传递构造函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆