c# - Ninject, using two way property injection to resolve cyclic dependency -
based on answers in question: cyclic dependency ninject , questions: ninject: give parent instance child being resolved both of these can use 2 way property injection resolve cyclic dependencies long change scope not default transient scope. tried doing that, i've got userservice
, groupservice
require each other (and please don't change classes or use third class, etc.!). i've got generic entityservicefactory
uses ninject so:
public static class entityservicefactory { public static tserviceclass getservice<tserviceclass>() tserviceclass : class { ikernel kernel = new standardkernel(); return kernel.get<tserviceclass>(); } }
and services:
public class groupservice : entityservice<grouprepository, group, dbcontext> { public userservice _userservice { private get; set; } public groupservice(grouprepository repository, userservice userservice) : base(repository) { userservice._groupservice = this; } public class userservice : entityservice<userrepository, user, dbcontext> { public groupservice _groupservice { private get; set; } public userservice(userrepository repository, groupservice groupservice) : base(repository) { groupservice._userservice = this; }
then per instructions in answers questions add following entityservicefactory
:
kernel.bind<groupservice>().toself().incallscope(); kernel.bind<userservice>().toself().incallscope();
but still error:
a cyclical dependency detected between constructors of 2 services.
am doing 2 way property injection correctly? how resolve this?
welp, turns out didn't understand answers in questions linked. didn't property injection @ all, ended doing this:
anytime there cyclic dependency remove 1 of cyclic-inducing services constructor , replace this:
private userservice _userservice; private userservice userservice { { return _userservice ?? (_userservice = entityservicefactory.getservice<userservice>()); } }
this ended being extremely close property injection (http://ninject.codeplex.com/wikipage?title=injection%20patterns). it's not optimal constructor injection, still isn't bad solution. have done (actual property injection):
private userservice _userservice; [inject] private userservice userservice { { return _userservice; } set { _userservice = value; } }
i chose way since doesn't require services have ninject specific code in case ever changed usage of it, called entityservicefactory.getservice
doing same thing [inject]
attribute.
Comments
Post a Comment