传递的参数不优于温莎城堡中的默认实现

本文关键字:城堡 默认 于温莎 实现 参数 | 更新日期: 2023-09-27 17:56:09

我想更喜欢参数实现而不是默认注册的实现,但它不起作用。

  • 事实上,文档建议它应该工作

错误首选项演示

    private static void Main(string[] args)
    {
        PassParamThatsAlreadyRegisteredAtResolutionTime();
        Console.ReadLine();
    }
    private static void PassParamThatsAlreadyRegisteredAtResolutionTime()
    {
        Console.WriteLine("Passing argument that is already registered 
                    does not take precedence over the default implementation");
        var container = new WindsorContainer();
        container.Register(
            Component.For<ISimpletonManager>()
                     .ImplementedBy<SimpletonManager>()
                     .LifestyleTransient()
                     .Properties(PropertyFilter.IgnoreAll));
        container.Register(Component.For<ISimpleton>().UsingFactoryMethod(() =>
                                     new Simpleton("Default Implementation"))
                                    .LifestyleTransient());
        // The above line could equally be the following, result is the same:
        // container.Register(Component.For<ISimpleton>()
        //                     .ImplementedBy<Simpleton>().LifestyleTransient());
        var runtimeConstructorParam = new Simpleton("Passed In Implementation");
        var runtimeArguments = new Arguments(
                                 new object[] {runtimeConstructorParam});
        var shouldBeManagerWithPassedInSimpleton = container
                             .Resolve<ISimpletonManager>(runtimeArguments);
        Console.WriteLine(shouldBeManagerWithPassedInSimpleton.Log);
    }

控制台输出

Passing argument that is already registered
does not take precedence over the default implementation
Birth With Child Simpleton: Default Implementation

如何反转偏好?

  • 我需要能够忽略默认注册的依赖项,而是使用提供的参数作为 ISimpleton 依赖项来解决温莎城堡?
  • 我是否需要实现自己的 IDependencyResolver?如何?
  • 或者动态参数在这里有用吗?

提供的依赖项 - 简单类

public class Simpleton : ISimpleton
{
    public Simpleton(string id)
    {
        Id = id;
    }
    public string Id { get; set; }
}

已解决类型 - 简单经理

public class SimpletonManager : ISimpletonManager
{
    private ISimpleton _child;
    public SimpletonManager(ISimpleton simpleton)
    {
        Child = simpleton;
    }
    public ISimpleton Child
    {
        get { return _child; }
        set
        {
            _child = value;
            Log = "Birth With Child Simpleton: " + Child.Id;
        }
    }
    public string Log { get; private set; }
}

[ 使用 Castle.Core.dll 和 Castle.Windsor.dll 3.1.0 (2012-08-05) ]

传递的参数不优于温莎城堡中的默认实现

与您的其他问题一样,依赖项的类型与Arguemnts公开的类型不同