Ninject:给父实例孩子得到解决 [英] Ninject: give the parent instance to a child being resolved

查看:143
本文介绍了Ninject:给父实例孩子得到解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的类层次结构:

I have this class hierarchy:

public interface ISR { }
public interface ICU { }
public interface IFI { }   

public class CU : ICU { }

public class SR : ISR
{
    public SR(IFI fi)
    {
        FI = fi;
    }

    public IFI FI { get; set; }
}

public class FI : IFI
{
    public FI(ISR sr, ICU cu)
    {
        SR = sr;
        CU = cu;
    }

    public ISR SR { get; set; }
    public ICU CU { get; set; }
}

public class Module : NinjectModule
{
    public override void Load()
    {
        Bind<ISR>().To<SR>();
        Bind<ICU>().To<CU>();
        Bind<IFI>().To<FI>();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var kernel = new StandardKernel(new Module());

        var sr = kernel.Get<ISR>();
    }
}

当我运行此代码,我有一个例外,因为我有一个循环依赖。该SR类需要IFI的实例,以注入完成,和FI类需要ISR的一个实例被注入。

When I run this code, I have an exception because I have a cyclic dependency. The SR class needs an instance of IFI to be injected in order to be completed, and the FI class needs an instance of ISR to be injected.

当然,使用。酒店的注入并不能解决这个问题。

Of course, using a property injection doesn't solve this issue.

我有一个特殊性,虽然我需要先建造ISR,它是这种情况下,必须考虑网络连接。所以ISR和国际金融机构需要共享范围。

I have a particularity though: I need ISR to be constructed first, and it is this instance which must be given to FI. So ISR and IFI need to share a scope.

您将如何解决与Ninject?

How would you solve that with Ninject?

推荐答案

要解决这个问题,最好的办法就是重构你的设计,去除循环依赖。几乎所有的循环依赖可以用一个适当的设计中除去。如果你有循环依赖通常有一个设计缺陷。最有可能你不履行单一职责原则。

The best way to handle this problem is to refactor your design to remove the cyclic dependency. Almost all cyclic dependencies can be removed with a proper design. If you have cyclic dependencies there is usually a design flaw. Most likely you do not fulfill the Single Responsibility Principle.

另外,你必须做双向财产注入,并确保它们具有相同的范围。例如。 InCallScope从NamedScope扩展。请参见 HTTP://www.planetgeek。 CH / 2010/12/08 /如何使用的最附加-ninject-范围-OF-namedscope /

Otherwise you have to do two way property injection and ensure they have the same scope. E.g. InCallScope from the NamedScope extension. See http://www.planetgeek.ch/2010/12/08/how-to-use-the-additional-ninject-scopes-of-namedscope/

这篇关于Ninject:给父实例孩子得到解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆