1

我希望参数实现优于默认注册的实现,但它不起作用。

不正确的偏好演示

    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 依赖项进行 Castle Windsor 解析?
  • 我需要实现自己的IDependencyResolver吗?如何?
  • 或者DynamicParameters在这里有用吗?

提供的依赖项 - Simpleton 类

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

    public string Id { get; set; }
}

已解析类型 - SimpletonManager

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

4

1 回答 1

2

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

于 2013-01-28T22:53:38.023 回答