Question

I'm having a problem with a cyclic dependency in a project using dependency injection. In looking around, it seems that the only way to avoid it, other than restructuring (I did some of that too), is to use property injection. I tried this, and it doesn't seem to help, but I'm not sure why. Here is the path that's causing issues.

Activation path:
  6) Injection of dependency IUserRepository into property UserRepository of type ModelFactory{UserRole}
  5) Injection of dependency IUserRoleFactory into parameter userRoleFactory of constructor of type UserRoleService
  4) Injection of dependency IUserRoleService into property UserRoleService of type InternalUserBehavior
  3) Injection of dependency IInternalUserBehavior into parameter internalUserBehavior of constructor of type UserRepository
  2) Injection of dependency IUserRepository into parameter userRepository of constructor of type HomeController
  1) Request for HomeController

Now, it seems to know it's using property injection, and all of the behaviors and factories are in the same scope (call scope right now, but I've tried thread scope too), as well as the UserRepository.

My understanding of the process is that it should be getting to 4, and be able to actually create the objects. At this point, it should have a reference to a HomeController, IUserRepository, and IInternalUserBehavior. Then it should work on 5, and insert the completed IUserRoleService into the InternalUserBehavior. Finally, it should insert the the previously instantiated user repository (since it's in the same scope) into the property in the ModelFactory

So I guess the short version of my question is: Why isn't property injection solving my cyclic dependency issue?

Était-ce utile?

La solution

It would help to see your code... but I think you are not understanding the process here.

At step 4), Ninject has just created InternalUserBehavior and is injecting the properties. In step 5), Ninject finds that it needs to create UserRoleService and proceeds to step 6) to create and then populate a ModelFactory{UserRole}.

I assume your classes look something like:

public class UserRoleService
{
   public UserRoleService(ModelFactory<UserRole> factory){}
}

public class ModelFactory<T>
{
    [Inject]
    public IUserRepository UserRepository { get; set; }
}

You definitely have a cyclic dependency, regardless of property injection. You need to resolve the cyclic dependency.

Another route would be to use Lazy<IUserRepository> with constructor injection to avoid the cyclic dependency. I have an answer that can help with that binding.

Effectively, your ModelFactory<> becomes:

public class ModelFactory<T>
{
    [Inject]
    public Lazy<IUserRepository> UserRepository { get; set; }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top