编程语言
首页 > 编程语言> > c# – StructureMap Generic Ctor命名实例

c# – StructureMap Generic Ctor命名实例

作者:互联网

更新

我用以下代码解决了这个问题,但这不是我正在寻找的解决方案.对于更通用的解决方案,这仍然是一个开放的奖励.如果我们有一个不是int值的表或键值的字符串,我们必须手动添加它以使其工作.

c.For(typeof(ILogDifferencesCommand<,>)).Use(typeof(LogDifferencesCommand<,>))
                .Ctor<ILogDifferencesLogger<int>>()
                .Named(AppSettingsManager.Get("logDifferences:Target"))
                .Ctor<string>()
                .Named(AppSettingsManager.Get("logDifferences:Target"));

原始问题

我有三种类型的记录器,我在容器中为它们定义了命名实例:

c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesAllLogger<>))
    .Named("all");
c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesNLogLogger<>))
    .Named("nlog");
c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesDatabaseLogger<>))
    .Named("database");

LogDifferencesCommand接收ILogDifferencesLogger<>作为唯一的论点:

public LogDifferencesCommand(ILogDifferencesLogger<TKey> logDifferencesLogger)
{
    this.logDifferencesLogger = logDifferencesLogger;
}

如何正确配置ILogDifferencesCommand<>根据应用程序设置获取正确的命名实例?现在我有这样的事情:

c.For(typeof(ILogDifferencesCommand<,>))
    .Use(typeof(LogDifferencesCommand<,>));

我遇到的问题是我无法接受Ctor<>因为我不能使用带有该签名的未绑定泛型,所以我不能使用Ctor的Named方法.

例如,我可以做这样的事情,但这不会触及所有可能的类型:

c.For(typeof(ILogDifferencesCommand<,>)).Use(typeof(LogDifferencesCommand<,>))
    .Ctor<ILogDifferencesLogger<int>>()
    .Named(AppSettingsManager.Get("logDifferences:Target"));

但问题是我必须处理系统使用的每种TKey类型.

类和接口定义

public class LogDifferencesCommand<TModel, TKey> : ILogDifferencesCommand<TModel, TKey>
    where TModel : class, IIdModel<TKey>
{
    public LogDifferencesCommand(ILogDifferencesLogger<TKey> logDifferencesLogger)
    {
        this.logDifferencesLogger = logDifferencesLogger;
    }
}

public interface ILogDifferencesCommand<TModel, TKey>
    where TModel : class, IIdModel<TKey>
{
    List<LogDifference> CalculateDifferences(TModel x, TModel y);

    void LogDifferences(TModel x, TModel y, string tableName, string keyField, string userId, int? clientId);

    void RegisterCustomDisplayNameObserver(WeakReference<ICustomDisplayNameObserver<TModel>> observer);

    void RegisterCustomChangeDateObserver(WeakReference<ICustomChangeDateObserver<TModel>> observer);
}

public interface ILogDifferencesLogger<TKey>
{
    void LogDifferences(string tableName, string keyField, string userId, TKey id, List<LogDifference> differences, int? clientId);
}

需要TKey的原因是因为IIdModel接口.

解决方法:

想到的一个选择:

var loggers = new Dictionary<string, ConfiguredInstance>();
loggers.Add("all", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesAllLogger<>)));
loggers.Add("nlog", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesNLogLogger<>)));
loggers.Add("database", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesDatabaseLogger<>)));
foreach (var kv in loggers) {
    // if you still need them named
    // if you only used names for this concrete scenario - you probably don't
    // so can remove it
    kv.Value.Named(kv.Key);
}
c.For(typeof(LogDifferencesCommand<>))
    .Use(typeof(LogDifferencesCommand<>))
    // add explicit instance as dependency
    .Dependencies.Add(typeof(ILogDifferencesLogger<>), loggers[AppSettingsManager.Get("logDifferences:Target")]); 

更新.正如我们在注释中所发现的那样,当LogDifferencesCommand具有多个类型参数时,这不适用于您的特定情况.由于某种原因(我认为这是一个错误) – 结构图尝试创建封闭的泛型类型ILogDifferencesLogger<>,但在这样做时 – 从LogDifferencesCommand传递泛型类型参数.也许值得在他们的github解决一个问题.您可以像这样解决它:

public class GenericTypesWorkaroundInstance : Instance
{
    private readonly Instance _target;
    private readonly Func<Type[], Type[]> _chooseTypes;
    public GenericTypesWorkaroundInstance(Instance target, Func<Type[], Type[]> chooseTypes) {
        _target = target;
        _chooseTypes = chooseTypes;
        ReturnedType = _target.ReturnedType;
    }

    public override Instance CloseType(Type[] types) {
        // close type correctly by ignoring wrong type arguments
        return _target.CloseType(_chooseTypes(types));
    }

    public override IDependencySource ToDependencySource(Type pluginType) {
        throw new NotSupportedException();
    }

    public override string Description => "Correctly close types over open generic instance";    
    public override Type ReturnedType { get; }
}

然后做

commandReg.Dependencies.Add(
    commandReg.Constructor.GetParameters().First(
        p => p.ParameterType.IsGenericType && p.ParameterType.GetGenericTypeDefinition() == typeof(ILogDifferencesLogger<>)).Name, 
        new GenericTypesWorkaroundInstance(
            loggers[AppSettingsManager.Get("logDifferences:Target")],
            // specify which types are correct
            types => types.Skip(1).ToArray()));

它有效,但我不能说我喜欢它.

标签:c,dependency-injection,net,structuremap,generics
来源: https://codeday.me/bug/20190607/1195595.html