Ninject: give the parent instance to a child being resolved

旧城冷巷雨未停 提交于 2019-12-23 13:03:21

问题


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

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.

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.

How would you solve that with Ninject?


回答1:


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.

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/



来源:https://stackoverflow.com/questions/6180280/ninject-give-the-parent-instance-to-a-child-being-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!