0
votes

I'm starting with Ninject and I use it in a MVC 4 scenario and configured my bindings in "NinjectWebCommon". And everything works fine.

Now I want in an library somehow get the kernel with the configuration from MVC app.

For example: In my MVC project I have class "BaseController" with a property

[Inject]
public IKernel Ninject { get; set; }

works perfect, means in every action in a controller which inherits from BaseController the property "Ninject" is fine instance and not null!

Now I have class "NinjectProxy" in my external lib with the exact same Property, but every time I create a new Instance of "NinjectProxy" the prop "Ninject" is null!

public class NinjectProxy
{
    [Inject]
    public IKernel Ninject { get; set; }


    public T Resolve<T>()
    {
        return Ninject.Get<T>();
    }
}

My complete solution looks like:

MVC app
- Reference on Common.dll and Ninject
- Contains ControllerBase
Common.dll
- This project contains the NinjectProxy class and have a reference on Ninject
- Here I want somehow get the kernel config that I configured in the mvc app to resolve dependecies
Implementation.dll
- References on Common.dll and Ninject

The lib is loaded in "NinjectWebCommon" with:

kernel.Load(Assembly.Load("lib"))

If this is important.

Have someone an Idea what I'm doing wrong?

1
How do you create an instance of NinjectProxy?Remo Gloor
normal, like var proxy = new NinjectProxy()SharpNoiZy
@ChristianNeuß You only need to do a .Load() if there is a Module in there to be Loaded into the Kernel. Key thing here is that DI containers don't intercept new. Also, your NinjectProxy is a bad idea - you should be depending on the actual thing you need because blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx Highly recommended is manning.com/seemann (Note it doesnt cover Ninject, but it's that good (and is about architecture more than low level) that it doesnt matter)Ruben Bartelink
In my common.dll I have an Interface IUnitOfWork which is in the Implementation.dll inherited by the class "ProjectUnitOfWork". And now I have to get in common.dll somehow the ProjectUnitOfWork over Ninject and the interface IUnitOfWork. But how should I load in the common.dll a module/mapping which is configured in the Implementation.dll?? common.dll don't know the implementation.dll.SharpNoiZy

1 Answers

0
votes

You are creating the instance manually using new This object is not handled by ninject and will never get dependencies.

Inject the instance somewhere instead or use a factory to have it created by ninject

But Ruben is absolutely right you are following a pattern you shouldn't use anyway. Instead configure Ninject completely in the bootstrapper. Either use conventions that match the whole project or reference all required assemblies and setup the bindings for them.