Using Ninject and Ninject.Extensions.Conventions with referenced assemblies

1k views Asked by At

I'm trying to get Ninject set up with an ASP.NET MVC 4 project.

I have 3 projects in my solution. The main MVC 4 web app, that has references to 2 supporting assemblies (My.Services.dll and My.Repository.dll). My.Services.dll also has a reference to My.Repository.dll.

I have added the Nuget packages: Ninject.MVC3 (version 3.0.0.6) and Ninject.Extensions.Conventions (version 3.0.0.11)

In the main web application I have a Home controller with the following constructor

public HomeController(IMyService myService)
{
    _myService = myService;
} 

The service has a constructor like so:

public MyService(IMyRepository myRepository)
{
    _myRepository = myRepository;
}

In my NinjectWebCommon file I have:

private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind(x =>
            {
                x.FromThisAssembly().SelectAllClasses().BindDefaultInterface();
                //x.FromAssemblyContaining<MyRepository>().SelectAllClasses().BindDefaultInterface();
                //x.FromAssemblyContaining<MyService>().SelectAllClasses().BindDefaultInterface();
                x.From("My.Repository", "My.Services").SelectAllTypes().BindDefaultInterface();

            });
        }         

If I run the application I get an error ("Value cannot be null.\r\nParameter name: first") on the last line of the RegisterServices method.

You can see in the code that I've also tried x.FromAssemblyContaining<MyRepository>().SelectAllClasses().BindDefaultInterface() to no avail.

Incidentally, If I put the 2 types, MyService and MyRepository in the web application and not in the satellite assemblies and remove the last line of RegisterServices then all dependencies are resolved and everything works correctly.

1

There are 1 answers

2
nemesv On BEST ANSWER

You can only have one From... expression inside in a kernel.Bind call.

So call your FromAssemblyContaining in different kernel.Bind statements, and it should work fine:

kernel.Bind(x => x.FromThisAssembly()
                  .SelectAllClasses().BindDefaultInterface());
kernel.Bind(x => x.FromAssemblyContaining<MyRepository>()
                  .SelectAllClasses().BindDefaultInterface());
kernel.Bind(x => x.FromAssemblyContaining<MyService>()
                  .SelectAllClasses().BindDefaultInterface());