Web API ContainerControlledLifetimeManager - not what expected - c#

I have an ASP.NET MVC application, which serving http pages and provides REST API using Web API.
I have a "service" class, which supposed to be a singleton and to be used both in ASP.NET MVC and Web API parts.
For dependency injection, I using Unity. I installed from NuGet Unity, Unity.AspNet.Mvc and Unity.AspNet.WebApi packages.
I registering my service as singleton:
container.RegisterType<IService, ServiceImp>(new ContainerControlledLifetimeManager());
What I see is that different instances of "ServiceImp" created for ASP.NET MVC and for Web API. The constructor called twice. It looks like there are two separate containers there...
All contents of UnityConfig.cs, UnityMvcActivator.cs and UnityWebApiActivator.cs remained unchanged as initial template, except the place where I register my services.
Any idea how to solve this issue? What I doing wrong?
UnityConfig.cs
namespace Management.App_Start
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IService, ServiceImp>(new ContainerControlledLifetimeManager());
}
}
}
UnityMvcActivator.cs
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Management.App_Start.UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(Management.App_Start.UnityWebActivator), "Shutdown")]
namespace Management.App_Start
{
/// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
public static class UnityWebActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
UnityWebApiActivator.cs
using System.Web.Http;
using Microsoft.Practices.Unity.WebApi;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Management.App_Start.UnityWebApiActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(Management.App_Start.UnityWebApiActivator), "Shutdown")]
namespace Management.App_Start
{
/// <summary>Provides the bootstrapping for integrating Unity with WebApi when it is hosted in ASP.NET</summary>
public static class UnityWebApiActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
// Use UnityHierarchicalDependencyResolver if you want to use a new child container for each IHttpController resolution.
// var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer());
var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
UPDATE 9.9.17
After some digging, I see that Application_Start called twice - first time when any http page requested and second time when REST API called. As a result, everything initialized twice, including Unity. Now I need to find out why this happens...

Related

Dependency injection integration with Unity.MVC, container.Resolve cannot be used with arguments of type

I'm trying to integrate Dependency Injection with Unity.MVC to my project. With the default configuration that Unity has, controllers works perfectly fine but I would like to implement DI en other classes...
This is the configuration I use:
I added this line on global.asax UnityMvcActivator.Start();
public static class UnityMvcActivator
{
/// <summary>
/// Integrates Unity when the application starts.
/// </summary>
public static void Start()
{
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));
DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>
/// Disposes the Unity container when the application is shut down.
/// </summary>
public static void Shutdown()
{
UnityConfig.Container.Dispose();
}
}
The last one comes by default and works perfectly with the controllers
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion
/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below.
// Make sure to add a Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your type's mappings here.
// container.RegisterType<IProductRepository, ProductRepository>();
if (Global.BOT_CONECTADO)
{
container.RegisterSingleton<ISeguidorRepository, DBSeguidorRepository>();
container.RegisterSingleton<IActivoRepository, DBActivoRepository>();
container.RegisterSingleton<ICategoriaRepository, DBCategoriaRepository>();
container.RegisterSingleton<IJuegoSecundarioRepository, DBJuegoSecundarioRepository>();
container.RegisterSingleton<ISaludosRepository, DBSaludosRepository>();
}
else
{
container.RegisterSingleton<ISeguidorRepository, FakeSeguidorRepository>();
container.RegisterSingleton<IActivoRepository, FakeActivoRepository>();
container.RegisterSingleton<ICategoriaRepository, FakeCategoriaRepository>();
container.RegisterSingleton<IJuegoSecundarioRepository, FakeJuegoSecundarioRepository>();
container.RegisterSingleton<ISaludosRepository, FakeSaludosRepository>();
}
//DependencyResolver.SetResolver(new IDConfigurador(container));
}
}
In the last one I added my registers, but When I try to use them on other contructors, those that are not controllers, they don't work. Looking for answers on google I found this solution that could help me:
container.Resolve()
I tried to use it but I get the following error ==> "The method 'IUnityContainer.Resolve(Type, string, params ResolverOverride[])' non generic cannot be used with arguments of type"
// CONSTRUCTOR
public RepositorioEncuesta()
{
// Error línea de abajo: El método 'IUnityContainer.Resolve(Type, string, params ResolverOverride[])' no
// genérico no se puede usar con argumentos de tipo
_activos = UnityConfig.Container.Resolve<IActivoRepository>();
_seguidores = new DBSeguidorRepository();
_juegos = new DBJuegoSecundarioRepository();
}
How could I use my DI integration to use it on other constructors? Why the Resolve method is not working?
PD: I also tried using a generic, but does not work either.
var activos = UnityConfig.Container.Resolve<IActivoRepository>();

Nuget update on Unity throwing 500 with "Make sure that the controller has a parameterless public constructor.",

SO I had a perfectly working WebApi service with Unity. I decided to take Nuget package update which overwrote the UnityConfig.cs, However, i added my code back and it works all fine when I try to run it from VisualStudio. Problem is when i deploy the bin and try to run the api from IIS. I get a 500, with following exception :
Exception.Source = System.Web.Http.Dispatcher.DefaultHttpControllerActivator
Exception.Message = An error occurred when trying to create a controller of type 'StateController'. Make sure that the controller has a parameterless public constructor.
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion
public static void RegisterTypes(IUnityContainer container)
{
string dbConnectionString = WebConfigurationManager.ConnectionStrings["abc"].ConnectionString;
StateRepository stateRepository = new StateRepository(dbConnectionString);
// Register a default (un-named) type mapping with a singleton lifetime
container.RegisterInstance<IStateRepository>(stateRepository);
}
}
Hers is my UnityWebApiActivator.cs
using System.Web.Http;
using Unity.AspNet.WebApi;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(PowerManagementServices.UnityWebApiActivator), nameof(PowerManagementServices.UnityWebApiActivator.Start))]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(PowerManagementServices.UnityWebApiActivator), nameof(PowerManagementServices.UnityWebApiActivator.Shutdown))]
namespace PowerManagementServices
{
/// <summary>
/// Provides the bootstrapping for integrating Unity with WebApi when it is hosted in ASP.NET.
/// </summary>
public static class UnityWebApiActivator
{
/// <summary>
/// Integrates Unity when the application starts.
/// </summary>
public static void Start()
{
// Use UnityHierarchicalDependencyResolver if you want to use
// a new child container for each IHttpController resolution.
// var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.Container);
var resolver = new UnityDependencyResolver(UnityConfig.Container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
/// <summary>
/// Disposes the Unity container when the application is shut down.
/// </summary>
public static void Shutdown()
{
UnityConfig.Container.Dispose();
}
}
}
what is missing ? As I mentioned this service was working perfectly before I took the nuget update. Now it works from VS but not when deployed.
Thanks In Advance.

interface and cannot be constructed on Unity config

I have trouble to use Unity on this project.
The error is
The current type, Business.Interfaces.IPersonnelBusiness, is an
interface and cannot be constructed. Are you missing a type mapping?
I've updated the Unity to thge latest version because of stackoverflow issueand I saw that RegisterComponents has changed to lazy loaded one
here is the Global asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Unity settings
//UnityConfig.RegisterComponents();
// For logging
//SetupSemanticLoggingApplicationBlock();
}
Here is the UnityConfig file:
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container
{
get
{
return container.Value;
}
}
#endregion
/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below.
// Make sure to add a Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your type's mappings here.
// container.RegisterType<IProductRepository, ProductRepository>();
container = new UnityContainer();
// Identity managment
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<PersonnelController>(new InjectionConstructor());
container.RegisterType<UsersAdminController>(new InjectionConstructor());
// Business Layer
container.RegisterType<ILogBusiness, LogBusiness>();
container.RegisterType<IAnomalyBusiness, AnomalyBusiness>();
container.RegisterType<ICockpitStatBusiness, CockpitStatsBusiness>();
container.RegisterType<IDocumentBusiness, DocumentBusiness>();
container.RegisterType<IEmailBusiness, EmailBusiness>();
container.RegisterType<IMessageBusiness, MessageBusiness>();
container.RegisterType<INatureBusiness, NatureBusiness>();
container.RegisterType<IPersonnelBusiness, PersonnelBusiness>();
container.RegisterType<ISAPBusiness, SAPBusiness>();
// Set resolver
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
Thanks folks
EDIT:
here is the stack and the code where it is thrown:
StackTrace:
[ResolutionFailedException: Resolution of the dependency failed, type = 'APPI.WEB.Controllers.HomeController', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, APPI.Business.Interfaces.IPersonnelBusiness, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:
Resolving APPI.WEB.Controllers.HomeController,(none)
Resolving parameter 'personnelRepo' of constructor APPI.WEB.Controllers.HomeController(APPI.Business.Interfaces.IPersonnelBusiness personnelRepo, APPI.Business.Interfaces.IAnomalyBusiness anomalyRepo, APPI.Business.Interfaces.IDocumentBusiness docRepo, APPI.Business.Interfaces.IMessageBusiness msgRepo, APPI.Business.Interfaces.ICockpitStatBusiness cockpitStatRepo, APPI.Business.Interfaces.INatureBusiness natureRepo)
Resolving APPI.Business.Interfaces.IPersonnelBusiness,(none)
]
Controller:
public class HomeController : BaseController
{
private readonly IPersonnelBusiness _IPersonnelBusinessRepo;
private readonly IAnomalyBusiness _IAnomalyBusinessRepo;
private readonly IDocumentBusiness _IDocumentBusinessRepo;
private readonly IMessageBusiness _IMessageBusinessRepo;
private readonly ICockpitStatBusiness _ICockpitStatBusinessRepo;
private readonly INatureBusiness _INatureBusinessRepo;
// Unity inject references
public HomeController(IPersonnelBusiness personnelRepo, IAnomalyBusiness anomalyRepo, IDocumentBusiness docRepo,
IMessageBusiness msgRepo, ICockpitStatBusiness cockpitStatRepo, INatureBusiness natureRepo)
{
_IPersonnelBusinessRepo = personnelRepo;
_IAnomalyBusinessRepo = anomalyRepo;
_IDocumentBusinessRepo = docRepo;
_IMessageBusinessRepo = msgRepo;
_ICockpitStatBusinessRepo = cockpitStatRepo;
_INatureBusinessRepo = natureRepo;
}
public HomeController()
{
}
public ActionResult Index()
{
return RedirectToActionPermanent("Cockpit", "Home");
}
There is also the UnityActivator that is called before starting app thanks to
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(APPI.WEB.UnityMvcActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(APPI.WEB.UnityMvcActivator), "Shutdown")]
UnityActivator:
public static class UnityMvcActivator
{
/// <summary>
/// Integrates Unity when the application starts.
/// </summary>
public static void Start()
{
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));
DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>
/// Disposes the Unity container when the application is shut down.
/// </summary>
public static void Shutdown()
{
UnityConfig.Container.Dispose();
}
}
As pointed out in the comments, the issue is that you are instantiating 2 different containers, once in your initializer:
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer(); // <-- new container here
RegisterTypes(container);
return container;
});
And once in your RegisterTypes method:
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below.
// Make sure to add a Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your type's mappings here.
// container.RegisterType<IProductRepository, ProductRepository>();
container = new UnityContainer(); // <-- new container here
...
The type mappings are added in the RegisterTypes method to a different instance than the container you are passing in as an argument.
To make it work right, you should remove the instantiation of the container in RegisterTypes so it can use the instance that is passed in the parameter.
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below.
// Make sure to add a Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your type's mappings here.
// container.RegisterType<IProductRepository, ProductRepository>();
// container = new UnityContainer(); // <-- Remove this
...

Replacing Mvvm Lights SimpleIoc with Unity IoC

I am having some trouble to get things up and running after replaced SimpleIoc with the unity IoC. I followed these instructions referring how to implement the IServiceLocator for unity.
However my application fails to function properly. For example I'm unable to get the dataGrids _selectedDevice to be anything else than null. With SimpleIoc, everything worked fine.
Here's my ViewModelLocator:
using System;
using System.Windows;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
namespace FxEditorDatabaseStructure.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
#region Constructor
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
// Register the IOC container as SimpleIoc
//ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
// Register Unity as the IOC container
var unityContainer = new UnityContainer();
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(unityContainer));
//If we wish use another IoC we must implement the IServiceLocator interface
// Create new UnitOfWork for all the views IOC - CREATED AT registration
//SimpleIoc.Default.Register<IUnitOfWork, UnitOfWork>(true);
unityContainer.RegisterType<IUnitOfWork, UnitOfWork>(new InjectionConstructor(new FxContext()));
/*
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<DeviceDatabaseViewModel>();
SimpleIoc.Default.Register<ProjectDeviceDatabaseViewModel>();
*/
unityContainer.RegisterType<MainViewModel>();
unityContainer.RegisterType<DeviceDatabaseViewModel>();
}
#endregion
#region ViewModels
[NotNull]
public MainViewModel MainViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
private set { if (value == null) throw new ArgumentNullException(nameof(value)); }
}
[NotNull]
public DeviceDatabaseViewModel DeviceDatabaseViewModel
{
get { return ServiceLocator.Current.GetInstance<DeviceDatabaseViewModel>(); }
private set { if (value == null) throw new ArgumentNullException(nameof(value)); }
}
/// <summary>
/// Retrieves this instance from the application's resources and exposes it to other objects.
/// </summary>
public static ViewModelLocator Instance
{
get
{
return Application.Current.Resources["Locator"] as ViewModelLocator;
}
}
#endregion
#region cleanup
public static void Cleanup()
{
// TODO Clear the ViewModels
}
#endregion
}
}
All the ViewModels call this IoC like this:
private readonly IUnitOfWork _context = ServiceLocator.Current.GetInstance<IUnitOfWork>();
Is there something wrong with this line?
unityContainer.RegisterType<IUnitOfWork, UnitOfWork>(new InjectionConstructor(new FxContext()));
I'm trying to initialise one instance of FxContext and share this to all the ViewModels which all call ServiceLocator.Current.GetInstance<IUnitOfWork>()
EDIT:
Basically I want to be able to use the same UnitOfWork for two different sets of database, like in the following:
var deviceDatabase = new DeviceContext();
var projectDatabase = new ProjectContext();
unityContainer.RegisterType<IUnitOfWork, UnitOfWork>(new InjectionConstructor(deviceDatabase));
unityContainer.RegisterType<IUnitOfWork, UnitOfWork>(new InjectionConstructor(projectDatabase));
Seems like to the answer to register the views similar to SimpleIoc is by following line:
unityContainer.RegisterType<MainViewModel>(new ContainerControlledLifetimeManager());
where the ContainerControlledLifetimeManager() was the key when using RegisterType method.

Issue using ASP.Net MVC 4 Web API with Ninject.Web.WebApi

I'm trying to use the new ASP.Net MVC 4 Web API project template with Ninject but have hit a wall on the following error:
Method 'GetFilters' in type 'Ninject.Web.WebApi.Filter.DefaultFilterProvider' from assembly 'Ninject.Web.WebApi, Version=3.0.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7' does not have an implementation.
I am creating a brand new project in Visual Studio 2010 using the ASP.Net MVC 4 -> Web API template and I am using the latest Ninject NuGet packages:
Ninject 3.0.1.10
Ninject.Web.Common 3.0.0.7
Ninject.Web.WebApi 3.0.0.2
I have attempted the solution presented in this question however I've not had any luck - if I remove the reference to Ninject.Web.WebApi then MVC never engages Ninject. I also notice they mention Ninject.MVC3 however I am using the new Ninject.WebApi plugin.
I am using the default binding code in NinjectWebCommon.cs that is created during the NuGet install and attempting to register one simple service in RegisterServices()
[assembly: WebActivator.PreApplicationStartMethod(typeof(mkts.web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(mkts.web.App_Start.NinjectWebCommon), "Stop")]
namespace mkts.web.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using mkts.service;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
//Test binding
kernel.Bind<IStudentService>().To<StudentService>();
}
}
}
My controller:
namespace mkts.web.Controllers
{
public class HomeController : Controller
{
private readonly IStudentService studentService;
public HomeController(IStudentService studentService)
{
this.studentService = studentService;
}
public ActionResult Index()
{
return View();
}
}
}
Many thanks in advance for any help with this.
Ninject.WebApi was written against the Beta and is deprecated now.
Remove that, install Ninject.MVC3.
Now you will need a homebrewed IDependencyResolver and IDependencyScope. I posted a walkthrough here - http://www.strathweb.com/2012/05/using-ninject-with-the-latest-asp-net-web-api-source/

Categories