Resolve/register Windsor 中字符串值的通用对象

Resolve/register generic object by string value in Windsor

我有一个接口IImportCommand<T>

public interface IImportCommand<T> where T : ImportModelBase
{
    DateTime Date { get; set; }
    List<T> Items { get; set; }
}

实现对象ImportEntityCommand<T>

public class ImportEntityCommand<T> : ICommand, IImportCommand<T> where T : ImportModelBase
{
    public DateTime Date { get; set; }
    public List<T> Items { get; set; }
}

以及 ImportModelBase

中的一些模型
UserImportModel : ImportModelBase
PersonImportModel : ImportModelBase

ImportEntityCommand

ImportUserCommand : ImportEntityCommand<UserImportModel>
ImportPersonCommand: ImportEntityCommand<PersonImportModel>

等等

要构建 ImportEntityCommand,我想在字符串参数为“user”时执行类似的操作

new ImportUserCommand()
{
    Date = body.Date.ToUniversalTime(),
    Items = body.Data.Select(d => d.ToObject<UserImportModel>()).ToList()
}

然后当“人”时

new ImportPersonCommand()
{
    Date = body.Date.ToUniversalTime(),
    Items = body.Data.Select(d => d.ToObject<PersonImportModel>()).ToList()
}

body 是 json 来自请求。

是否可以根据输入字符串注册我的界面和实体以创建所需的命令对象?


最简单的解决方案是使用 switch 语句,但我想要更优雅的东西。

不应使用依赖注入注册命令,但您可以注册 Factory 以根据输入字符串创建命令。

不使用 switch 语句执行此操作的一种方法是将工厂方法添加到内部 Dictionary,其中键是输入字符串。

也许这样的事情可以帮助您入门;

工厂(向DI注册)

public interface ICommandFactory
{
    ICommand Create(string type, DateTime dateTime, string json);
}

public class CommandFactory : ICommandFactory
{
    private readonly Dictionary<string, Func<DateTime, string, ICommand>> _dictionary = new ()
    {
        { "user", (dateTime, json) => new ImportUserCommand(dateTime, json) },
        { "person", (dateTime, json) => new ImportPersonCommand(dateTime, json) }
    };

    public ICommand Create(string type, DateTime dateTime, string json) => _dictionary[type](dateTime, json);
}

命令和模型(未注册)

public interface ICommand
{
    DateTime Date { get; set; }
}

public class Command<T> : ICommand
{
    protected Command(DateTime dateTime, string json) { /* Set data from json */ }

    public DateTime Date { get; set; }
    public List<T> Items { get; set; }
}

public class ImportUserCommand : Command<UserImportModel>
{
    public ImportUserCommand(DateTime dateTime, string json) : base(dateTime, json) { }
}

public class ImportPersonCommand : Command<PersonImportModel>
{
    public ImportPersonCommand(DateTime dateTime, string json) : base(dateTime, json) { }
}

public class UserImportModel { }
public class PersonImportModel { }