【问题标题】:autofac - configuration to set a property value based on generic type while resolving constructor parameterautofac - 在解析构造函数参数时根据泛型类型设置属性值的配置
【发布时间】:2017-03-10 23:48:44
【问题描述】:

我有一个定义如下的类:

public class CommandBase<T>
{
    public string CommandText { get; set; }
}

public class CommandService : ICommandService
{
    public CommandService(CommandBase<SomeClass> command)
    {
        //some other code
    }
}

是否有可能使用 Autofac 创建一个配置,当 CommandService 的构造函数参数是 CommandBase&lt;SomeClass&gt; 时,CommandText 值是“SomeCommand”,而当它是 CommandBase&lt;SomeOtherClass&gt; 时,CommandText 值比如说“SomeOtherCommand”。

那么,简而言之,我可以在 autofac 中配置来解析在构造函数参数中解析的对象的属性值吗,基于泛型类型?

编辑:

命令文本的值是一个长查询字符串,来自另一个单例类。

【问题讨论】:

  • 您能否更新您的问题以显示 实际 用例?你希望这个CommandText返回什么样的信息?这是运行时数据吗? CommandBase&lt;T&gt; 是什么?那是数据容器(如 DTO 或消息)还是有行为的东西?

标签: c# generics autofac


【解决方案1】:

答案是肯定的。您可以使用 RegisterGeneric

builder.RegisterGeneric(typeof(CommandBase<>)).AsSelf();

如果你想注册到接口 -

builder.RegisterGeneric(typeof(CommandBase<>)).As(typeof(ICommandBase<>));

【讨论】:

  • CommandText的值如何配置解析基于此?
  • 由于 CommandText 的值来自另一个单例类,您可以通过构造函数注入将该单例类注入 CommandBase。
【解决方案2】:

一种解决方案是更改 CommandBase 实现

public class CommandBase<T>
{
    public CommandBase(CommandRetriever retriever)
    {
        this.CommandText = new Lazy<String>(() => retriever.GetCommand(typeof(T)); 
    }

    private readonly Lazy<String> _commandText; 

    public String CommandText { 
        get {
            return this._commandText.Value; 
        }
    }
}

顺便说一句,根据我的理解,我会做这样的事情:

public interface ICommand
{
    String CommandText { get; }
}

public abstract class CommandBase<T> : ICommand
{
    public CommandBase(CommandRetriever retriever)
    {
        this._commandText = new Lazy<String>(() => retriever.GetCommand(typeof(T)));
    }

    private readonly Lazy<String> _commandText;

    public virtual String CommandText => this._commandText.Value;
}

public class PersonCommand : CommandBase<Person>
{
    public PersonCommand(CommandRetriever retriever) : base(retriever)
    { }
}

像这样你的CommandService 不再需要是通用的,这可以简化很多事情

public class CommandService : ICommandService
{
    public CommandService(ICommand command)
    {
        //some other code
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多