如何为wpf应用程序设置容器以共享每个图的依赖关系

时间:2015-04-13 14:28:52

标签: c# wpf mvvm castle-windsor

我有一个结构良好且大型的wpf mvvm应用程序,它使用城堡windsor作为容器。

我的root有各种操作与类型化工厂和存储库。 我希望我的所有操作都能在每个图表中共享依赖项。

如果我的所有操作都只使用了打包视图模型的类型化工厂,那么使用BoundTo<注册存储库就很容易了。 ViewModelBase> ()...

我目前的解决方案使用 BoundTo<对象>()有它的缺点,例如,所有根动作共享存储库。

我搜索了解决方案,但没找到任何解决方案。 我更喜欢使用城堡温莎作为我的容器。 任何人都可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

我所做的是使用BoundTo。只要你想拥有它的任何类,它自己的图形实现ISomeMarkerInterface,它只是一个空的接口类。如果我没有弄错,你需要注册ISomeMarkerInterface作为该类的附加接口。

祝你好运, Marwijn。

==编辑==

如果您真的需要这种灵活性,请尝试使用CustomRootSelector:

using System.Diagnostics;
using System.Linq;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace ConsoleApplication3
{
    public class Root1
    {
        public Dep1 D1 { get; set; }
        public Dep1 D2 { get; set; }
        public Dep2 D3 { get; set; }
        public Dep2 D4 { get; set; }
    }

    public class Root2
    {
        public Dep1 D1 { get; set; }
        public Dep1 D2 { get; set; }
        public Dep2 D3 { get; set; }
        public Dep2 D4 { get; set; }
    }

    public class Dep1
    { 
    }

    public class Dep2
    { 
    }

    public class CustomScopeRootSelector
    {
        private readonly object[] _roots;

        public CustomScopeRootSelector(params object[] roots)
        {
            _roots = roots;
        }

        public IHandler Selector(IHandler[] resolutionStack)
        {
            return resolutionStack.FirstOrDefault(h => _roots.Contains(h.ComponentModel.Implementation));
        }
    }


    class Program
    {
        static void Main()
        {
            var container = new WindsorContainer();
            var rootSelector = new CustomScopeRootSelector(typeof (Root1), typeof (Root2));
            container.Register(
               Component.For<Root1>().LifestyleTransient(),
               Component.For<Root2>().LifestyleTransient(),
               Component.For<Dep1>().LifestyleBoundTo(rootSelector.Selector),
               Component.For<Dep2>().LifestyleBoundTo(rootSelector.Selector)
               );
            var r1 = container.Resolve<Root1>();
            var r2 = container.Resolve<Root2>();

            Debug.Assert(r1.D1 == r1.D2);
            Debug.Assert(r1.D1 != r2.D1);
        }
    }
}

我希望代码解释得足够多。如果您有任何疑问,请告诉我。

相关问题