Dependency Injection on Global.asax compilation error - c#

I'm having compilation error when calling my service in global.asax. Im using UnityMvc as my DI. It was working when called in my controllers but no in Global.asax. Here is the error.
Compiler Error Message: CS7036: There is no argument given that corresponds to the required formal parameter 'genreService' of 'MvcApplication.MvcApplication(IGenreService)'
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
private readonly IGenreService _genreService;
public MvcApplication(IGenreService genreService)
{
_genreService = genreService;
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
GenreService.cs
public partial class GenreService : IGenreService
{
private readonly IRepository<Genre> _genreRepository;
private readonly IRepository<GameGenre> _gameGenreRepository;
public GenreService(IRepository<Genre> genreRepository, IRepository<GameGenre> gameGenreRepository)
{
_genreRepository = genreRepository;
_gameGenreRepository = gameGenreRepository;
}
// methods
}
IGenreService.cs
public partial interface IGenreService
{
// interface
}
UnityConfig.cs
using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Data.Entity;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using GameCommerce.Infrastructure.Services.GameLibrary;
using GameCommerce.Infrastructure;
using Microsoft.AspNet.Identity.EntityFramework;
using GameCommerce.Infrastructure.ApplicationUsers;
using System.Web;
using GameCommerce.Infrastructure.Services.Message;
namespace GameCommerce.Web.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)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your types here
// container.RegisterType<IProductRepository, ProductRepository>();
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new InjectionConstructor(new ApplicationDbContext()));
container.RegisterType<Areas.Admin.Controllers.AccountController>(new InjectionConstructor());
container.RegisterType<Controllers.AccountController>(new InjectionConstructor());
container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
container.RegisterType<IGameService, GameService>();
container.RegisterType<IGenreService, GenreService>();
container.RegisterType<IGameDeveloperService, GameDeveloperService>();
container.RegisterType<IGamePublisherService, GamePublisherService>();
container.RegisterType<IMessageService, MessageService>();
}
}
}

Try with the below code:
using Microsoft.Practices.Unity;
public class MvcApplication : System.Web.HttpApplication
{
private readonly IGenreService _genreService;
public MvcApplication()
{
_genreService = GameCommerce.Web.App_Start.UnityConfig.GetConfiguredContainer().Resolve<IGenreService>();
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
DepedencyResolver in MVC by default is used for resolution in controllers, so here we are using explicity using the Container for resolution in 'MvcApplication'.

Related

Adding Unity to MVC WebApi app

Hello all I've Added Unity to an MVC app. it seems that DI is working with the MVC Portion of the app but i cannot figure out why it wont work with the API part of the application.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name:"DefaultApi",
routeTemplate:"api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
}
}
public static class UnityMvcActivator
{
/// <summary>
/// Integrates Unity when the application starts.
/// </summary>
public static void Start(HttpConfiguration configuration)
{
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();
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Address", action = "Index", id = UrlParameter.Optional }
);
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
BundleConfig.RegisterBundles(BundleTable.Bundles);
RouteConfig.RegisterRoutes(RouteTable.Routes);
UnityMvcActivator.Start(GlobalConfiguration.Configuration);
}
I am just trying to get a repository to work in the web api but i keep getting
An error occurred when trying to create a controller of type 'AddressSearchController'. Make sure that the controller has a parameterless public constructor.",
this error. I have seen a few posts about this. I have tried them and still cannot get this to work. Does anyone have any suggestions?
public class AddressSearchController:_SimpleController<Address>
{
public AddressSearchController(IRepository<Address> addressRepository) : base(addressRepository)
{
}
[HttpPost]
[Route("api/AddressSearch/Search")]
public IHttpActionResult Search([FromBody] AddressSearchDto addressSearchDto)
{
var addresses = new List<Address>()
{
CreateAddress(1,"Main St", 123),
CreateAddress(2,"Main St", 124),
CreateAddress(3,"Main St", 125),
};
return Ok(addresses);
}
static Address CreateAddress(int id,string street, int houseNumber)
{
return new Address()
{
Id = id,
StreetName = street,
HouseNumber = houseNumber
};
}
}
public static void RegisterTypes(IUnityContainer container)
{
RegisterInstances(container);
}
private static void RegisterInstances(IUnityContainer container)
{
container.RegisterType<IAddressContext, AddressContext>();
container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
}
using System;
using Address_Tracker.Data.Context;
using Address_Tracker.Data.Context.Interfaces;
using Address_Tracker.Data.Repositories;
using Unity;
namespace Address_Tracker
{
/// <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
/// <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)
{
RegisterInstances(container);
}
private static void RegisterInstances(IUnityContainer container)
{
container.RegisterType<IAddressContext, AddressContext>();
container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
}
}
}
Your AddressSearchController should have a default constructor, or if you have no default / parameterless constructor, then please pass interfaces instead of concrete classes in AddressSearchController.
I believe you may have such a scenario:
public class AddressSearchController : ApiController
{
public AddressSearchController(SomeClassParameter obj)
{
//some code
}
}
What you want actually is ether this:
public class AddressSearchController : ApiController
{
public AddressSearchController() // add default ctor
{
}
public AddressSearchController(SomeClassParameter obj)
{
//some code
}
}
or this:
Register the interface ISomeClassParameter for type SomeClassParameter in Unity
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents(); // <----- Add this line
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Register component:
container.RegisterType<ISomeClassParameter , SomeClassParameter >();
and do constructor injection :
public class AddressSearchController : ApiController
{
public AddressSearchController(ISomeClassParameter obj)
{
//some code
}
}
Also, make sure you have the WebApi version of Unity
I tried it out, it worked for me:

unable to get default constructor while using Unity

Problem
I am trying to test my service. when I run test it show this error and test failed. my unity config class is in my asp.net mvc project and my test is in different project I don't know where I am doing wrong.
unable to get default constructor for Class servicetest
ServiceTest
[TestClass]
public class ImportServiceTests
{
private readonly IImportService _importService;
private readonly IUnitOfWork _unitOfWork;
public ImportServiceTests(IImportService importService, IUnitOfWork unitOfWork)
{
_importService = importService;
_unitOfWork = unitOfWork;
}
[TestMethod]
public void ImportCategories()
{
string filePath = Path.GetFullPath(#"E:\categories.xlsx");
if (File.Exists(filePath))
{
Stream data = File.OpenRead(filePath);
string fileName = Path.GetFileName(filePath);
_importService.ImportCategoriesFromXlsx(data);
}
}
}
UnityConfig
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)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your types here
// container.RegisterType<IProductRepository, ProductRepository>();
container.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager());
container.RegisterType<IImportService, ImportService>(new PerRequestLifetimeManager());
container.RegisterType<IDataContext, PriceHunterDataContext>(new PerRequestLifetimeManager());
}
}

Autofac service not registered (Microsoft Bot Framework)

I am trying (in vain) to register my Dialog.
My Dialog's constructor look like this:
// Private fields
protected readonly IGroupProvider _groupProvider;
protected readonly IProductProvider _productProvider;
protected IList<GroupResponseModel> _groups;
protected IList<ProductResponseModel> _products;
/// <summary>
/// Default constructor
/// </summary>
public PiiiCKDialog(IGroupProvider groupProvider, IProductProvider productProvider)
{
SetField.NotNull(out this._groupProvider, nameof(groupProvider), groupProvider);
SetField.NotNull(out this._productProvider, nameof(productProvider), productProvider);
}
In my PiiiCKModule, I have done this:
public class PiiiCKModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
// Register our Luis Attribute
builder.Register(c => new LuisModelAttribute("key", "key")).AsSelf().AsImplementedInterfaces().SingleInstance();
// Register some singleton services
builder.RegisterType<GroupProvider>().Keyed<IGroupProvider>(FiberModule.Key_DoNotSerialize).AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ProductProvider>().Keyed<IProductProvider>(FiberModule.Key_DoNotSerialize).AsImplementedInterfaces().SingleInstance();
// Register the top level dialog
builder.RegisterType<PiiiCKDialog>().As<LuisDialog<object>>().InstancePerDependency();
}
}
And in my Global.ascx.cs file I have followed the Autofac quick start and created this:
public class WebApiApplication : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// Create our builder
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
// Register the alarm dependencies
builder.RegisterModule(new PiiiCKModule());
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// OPTIONAL: Register the Autofac filter provider.
builder.RegisterWebApiFilterProvider(config);
// Build.
var container = builder.Build();
// Set the dependency resolver to be Autofac.
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
// Configure our Web API
GlobalConfiguration.Configure(WebApiConfig.Register);
}
public static ILifetimeScope FindContainer()
{
var config = GlobalConfiguration.Configuration;
var resolver = (AutofacWebApiDependencyResolver)config.DependencyResolver;
return resolver.Container;
}
}
My controller looks like this:
[BotAuthentication]
public class MessagesController : ApiController
{
// TODO: "service locator"
private readonly ILifetimeScope scope;
public MessagesController(ILifetimeScope scope)
{
SetField.NotNull(out this.scope, nameof(scope), scope);
}
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity model, CancellationToken token)
{
// one of these will have an interface and process it
switch (model.GetActivityType())
{
case ActivityTypes.Message:
try
{
// Create our conversation
await Conversation.SendAsync(model, () => scope.Resolve<PiiiCKDialog>());
}
catch (Exception ex)
{
}
break;
case ActivityTypes.ConversationUpdate:
case ActivityTypes.ContactRelationUpdate:
case ActivityTypes.Typing:
case ActivityTypes.DeleteUserData:
default:
Trace.TraceError($"Unknown activity type ignored: { model.GetActivityType() }");
break;
}
return new HttpResponseMessage(HttpStatusCode.Accepted);
}
}
But when I run my application, I get this error:
'PiiiCKBot.Business.PiiiCKDialog' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
As far as I can tell, I am registering my component. Does anyone have any clue why this is not working?
Ok, I managed to get this to work:
First, in my Message controller I changed it to this:
await Conversation.SendAsync(model, () => scope.Resolve<IDialog<object>>());
It also appears that I have to add the [NonSerialized] attribute to the providers, which I was certain I wounldn't have to because of the Module where I do this:
builder.RegisterType<GroupProvider>().Keyed<IGroupProvider>(FiberModule.Key_DoNotSerialize).AsImplementedInterfaces().SingleInstance();
But it won't work without the data attribute.
Finally, in my Module when I register the Dialog, it should be registered like this:
builder.RegisterType<PiiiCKDialog>().As<IDialog<object>>().InstancePerDependency();

Make sure that the controller has a parameterless public constructor using Ninject

Here is the issue at hand:
While calling my CustomerController through the URL, I get the following exception:
ExceptionMessage:
An error occurred when trying to create a controller of type
'CustomerController'. Make sure that the controller has a
parameterless public constructor.
I am using the following url's:
http://localhost:55555/api/Customer/
http://localhost:55555/api/Customer/8
Please note: The /api/Customer/ call were working before I refactored the logic into a business class and implemented dependency injection.
My research suggests that I am not registering my interface and class correctly with Ninject, but not sure what step I am missing.
Researched Links:
Make sure that the controller has a parameterless public constructor error
Make sure that the controller has a parameterless public constructor in Unity
Here is my question What is causing this exception? I am registering my interface/class within Ninject, but it doesn't seem to recognize the mapping correctly. Any thoughts?
Customer Controller
public class CustomerController : ApiController
{
private readonly ICustomerBusiness _customerBusiness;
public CustomerController(ICustomerBusiness customerBusiness)
{
_customerBusiness = customerBusiness;
}
// GET api/Customer
[HttpGet]
public IEnumerable<Customer> GetCustomers()
{
return _customerBusiness.GetCustomers();
}
// GET api/Customer/Id
[HttpGet]
public IEnumerable<Customer> GetCustomersById(int customerId)
{
return _customerBusiness.GetCustomerById(customerId);
}
}
Customer Business
public class CustomerBusiness : ICustomerBusiness
{
private readonly DatabaseContext _databaseContext = new DatabaseContext();
public IEnumerable<Customer> GetCustomers()
{
return _databaseContext.Customers;
}
public IQueryable<Customer> GetCustomerById(int customerId)
{
return _databaseContext.Customers.Where(c => c.CustomerId == customerId);
}
}
Customer Business Interface
public interface ICustomerBusiness
{
IQueryable<Customer> GetCustomerById(int customerId);
IEnumerable<Customer> GetCustomers();
}
NinjectWebCommon
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using MyReservation.API;
using MyReservation.API.Business;
using Ninject;
using Ninject.Web.Common;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]
namespace MyReservation.API
{
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();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICustomerBusiness>().To<CustomerBusiness>();
}
}
}
For the same problem I installed the nuget packages
ninject
ninject.web.common
ninject.web.common.webhost
ninject.web.webapi
ninject.web.webapi.webhost
and worked

How to use Ninject with WebApi?

I need to use Ninject on a Web APi app (I created it using the empty web api template).
I installed the following nuget package :
Ninject.Web.WebApi
Ninject.MVC3
Here is my application_start
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
My Ninject.Web.Common
[assembly: WebActivator.PreApplicationStartMethod(typeof(rb.rpg.backend.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(rb.rpg.backend.App_Start.NinjectWebCommon), "Stop")]
namespace rb.rpg.backend.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using Raven.Client;
using RemiDDD.Framework.Cqrs;
using System.Web.Http.Dependencies;
using System.Web.Http;
using System.Collections.Generic;
using Ninject.Web.WebApi;
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);
//System.Web.Mvc.DependencyResolver.SetResolver(new LocalNinjectDependencyResolver(kernel));
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(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)
{
kernel.Bind<IDocumentSession>()
.ToMethod(ctx => WebApiApplication.DocumentStore.OpenSession())
.InRequestScope();
kernel.Bind<MessageProcessor>()
.ToMethod(ctx =>
{
var MessageProcessor = new MessageProcessor(kernel);
/*...*/
return MessageProcessor;
})
.InSingletonScope();
}
}
}
When I rebuild the app the first loading is fine, my contrller gets my IDocumentSession. But when I reload the same page, I got the errror
"the type .. has no default constructor"
Here is how I set it up in my Web API projects:
Download regular Ninject from nuget.org
PM> Install-Package Ninject
In your Web API project add new folder named Infrastructure in that folder create 2 files:
NInjectDependencyScope.cs with content:
public class NInjectDependencyScope : IDependencyScope
{
private IResolutionRoot _resolutionRoot;
public NInjectDependencyScope(IResolutionRoot resolutionRoot)
{
_resolutionRoot = resolutionRoot;
}
public void Dispose()
{
var disposable = _resolutionRoot as IDisposable;
if (disposable != null)
disposable.Dispose();
_resolutionRoot = null;
}
public object GetService(Type serviceType)
{
return GetServices(serviceType).FirstOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
var request = _resolutionRoot.CreateRequest(serviceType, null, new IParameter[0], true, true);
return _resolutionRoot.Resolve(request);
}
}
and NInjectDependencyResolver.cs with content:
public class NInjectDependencyResolver : NInjectDependencyScope, IDependencyResolver
{
private IKernel _kernel;
public NInjectDependencyResolver(IKernel kernel) : base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NInjectDependencyScope(_kernel.BeginBlock());
}
}
In Global.asax file in Application_Start() method add:
//Ninject dependency injection configuration
var kernel = new StandardKernel();
kernel.Bind<IXyzRepository>().To<EFXyzRepository>();
GlobalConfiguration.Configuration.DependencyResolver = new NInjectDependencyResolver(kernel);
so that your final Global.asax file will look like this:
public class XyzApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//Ninject dependency injection configuration
var kernel = new StandardKernel();
//Your dependency bindings
kernel.Bind<IXyzRepository>().To<EFXyzRepository>();
GlobalConfiguration.Configuration.DependencyResolver = new NInjectDependencyResolver(kernel);
}
}
An that is it!
Here is the example of usage:
public class PersonController : ApiController
{
private readonly IXyzRepository repository;
public PersonController(IXyzRepository repo)
{
repository = repo;
}
...
...
...
I hope this helps.

Categories

Resources