I have two Web API 2 projects, ProjectAand ProjectBinside one solution.
These are independent projects. I want to use ninject in both, but these lines cause problems.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ProjectA.App_Start.NinjectWebCommon), "Start")]
and
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ProjectB.App_Start.NinjectWebCommon), "Start")]
Even if I only have ProjectA as the launch, both NinjectWebCommon classes will execute. And whatever the last one (usually ProjectB), it overwrites what was done first.
An exception:
When called bootstrapper.Initialize(CreateKernel)in ProjectB, I get -
"Sequence contains no elements"
How can I create two projects, one of which or both, can be run projects in one solution using ninject?
The code
This is mine NinjectWebCommon, it is almost identical for ProjectA and ProjectB, only registered services are different.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ProjectA.WebApi.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(ProjectA.WebApi.App_Start.NinjectWebCommon), "Stop")]
namespace ProjectA.WebApi.App_Start
{
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
var mapper = AutoMapperConfig.SetupMappings();
kernel.Bind<IMapper>().ToConstant(mapper);
kernel.Bind<IFoo>().To<Foo>();
}
}
}