传递的参数不比Castle Windsor的默认实现更受青睐

时间:2013-01-27 18:39:45

标签: c# .net dependency-injection castle-windsor constructor-injection

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

不正确的偏好演示

    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; }
}

[Using Castle.Core.dll and Castle.Windsor.dll 3.1.0 (2012-08-05)]

1 个答案:

答案 0 :(得分:2)

your other question一样,依赖项的类型与Arguemnts正在公开的类型不同