NinJect Get Service is not returning an instance of the class - asp.net-mvc-4

I am working with MVC 4.0 & .net 4.0 and wish to use Ninject.
I have a static class, in which objects are created. I can NOT make the static calling class non-static!
I am trying to get an instance based on this binding
Bind<ClinicWebsite.ViewModels.ISelectionEngine>)
.To<ClinicWebsite.ViewModels.Genric_SelectionEngine>();
in the static class I call:
ClinicWebsite.ViewModels.Generic_SelectionEngine myService =
ClinicWebsite.App_Start.NinjectWebCommon.Kernel
.GetService(typeof(ClinicWebsite.ViewModels.ISelectionEngine))
as ClinicWebsite.ViewModels.Generic_SelectionEngine;
but when I examine "myservice" I get:
The name 'myservice' does not exist in the current context
What could I be doing wrong, or is there another way to explicitly create an instance with Ninject (again, cannot get rid of static calling class)
NinjectWebCommon
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
private static readonly StandardKernel kernel = new StandardKernel();
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()
{
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
//DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
Bind<ClinicWebsite.ViewModels.ISelectionEngine>().To<ClinicWebsite.ViewModels.Generic_SelectionEngine>();
}
public static IKernel Kernel
{
get
{
return kernel;
}
}
}

I found the answer.
because this is in a static class I need to make"myservice" a static member of the class and then assign to it.

Related

Ninject Interception in a IIS hosted WCF application

I have a working WCF application hosted in IIS (.svc), using Ninject (Ninject.Web.Common) for dependency injection. All is well and good, works great. However I am trying to implment interception on the service endpoints and am getting a ServiceActiviationException. I've included the ninject extensions for wcf, interception, and interception.dynamic proxy as well as castle.core, so I'm not really sure what I'm missing here. Any ideas?
UPDATE: I was able to get past the service validation exception but I am now getting the following error:
Can not instantiate proxy of class: MyNameSpace.CustomerService.
Could not find a parameterless constructor.
My NinjectWebCommon contents:
public 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 PostStart()
{
// Inject the WITS Application Security service into the ApplicationSecurityRoleProvider
//_kernel.Inject(Roles.Provider);
}
public static void Stop()
{
Bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel(
new AutoMapperModule(),
new CustomerServiceModule(),
new AccountServiceModule());
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<LoggingInterceptor>().ToSelf().InRequestScope();
kernel.Bind<CustomerService>().ToSelf().Intercept().With<LoggingInterceptor>();
}
And a simple interceptor (Ive tried this also just implementing IInterceptor to no avail):
public class LoggingInterceptor : SimpleInterceptor
{
/// <summary>
/// Intercepts the specified invocation.
/// </summary>
/// <param name="invocation">The invocation to intercept.</param>
protected override void BeforeInvoke(IInvocation invocation)
{
Debug.WriteLine("Running " + invocation.ReturnValue);
base.BeforeInvoke(invocation);
}
public new void Intercept(IInvocation invocation)
{
try
{
base.Intercept(invocation);
}
catch (Exception e)
{
Debug.WriteLine("Exception: " + e.Message);
}
}
protected override void AfterInvoke(IInvocation invocation)
{
Debug.WriteLine("After Method");
base.AfterInvoke(invocation);
}
}

Error activating service - Ninject

I am getting the following error whenever I try to inject one of my service's dependency into the MVC controller:
Error activating IFeedService No matching bindings are available, and the type is not self-bindable.
Activation path:
2) Injection of dependency IFeedService into parameter svc of constructor of type FeedController
1) Request for FeedController
Suggestions:
1) Ensure that you have defined a binding for IFeedService.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
======================================================================
Here's how my code looks like:
ObjectFactory.cs
private static void RegisterServices(IKernel kernel)
{
// Contexts
kernel.Bind<IEntityObjectContext>().To<Entities>();
kernel.Bind<IAzureObjectContext>().To<AzureTableObjectContext>();
// Repositories
kernel.Bind<IEFRepository>().To<EFRepository>();
kernel.Bind<IAzureRepository>().To<AzureRepository>();
// Services
kernel.Bind<IFeedService>().To<FeedService>();
}
IEFRepository.cs
public interface IEFRepository : IDisposable
{
void SetContext(IEntityObjectContext context);
IQueryable<T> GetAll<T>() where T : class;
}
EFRepository.cs
public class EFRepository : IEFRepository
{
internal IEntityObjectContext context;
private Dictionary<Type, object> objectSets;
public EFRepository(IEntityObjectContext context)
{
this.context = context;
objectSets = new Dictionary<Type, object>();
}
public void SetContext(IEntityObjectContext context)
{
this.context = context;
}
}
IFeedService.cs
public interface IFeedService : IDisposable
{
IQueryable<FeedItem> GetPosts();
}
FeedService.cs
public class FeedService : IFeedService
{
private IEntityObjectContext _context;
private readonly IEFRepository _repo;
public FeedService(IEntityObjectContext context,
IEFRepository repo)
{
_context = context;
_repo = repo;
_repo.SetContext(_context);
}
public IQueryable<FeedItem> GetPosts()
{
using (_repo)
{
return _repo.GetAll<FeedItem>().Take(10);
}
}
}
FeedController.cs
public class FeedController : Controller
{
private readonly IFeedService _svc;
public FeedController(IFeedService svc)
{
_svc = svc;
}
}
As you can see, there are some nested dependency there in action. Not sure though, what needs to be added/removed for this bit to work.
Note: The error is thrown whenever I request the Feed/FetchFeed path. I also tried to comment out the FeedService's constructor portion to see if the nested dependencies are creating any problem, but again same error was thrown.
EDIT 1:
Rest of the code for the ObjectFactory.cs
class ObjectFactory
{
static ObjectFactory()
{
RegisterServices(kernel);
}
static IKernel kernel = new StandardKernel();
public static T GetInstance<T>()
{
return kernel.Get<T>();
}
private static void RegisterServices(IKernel kernel)
{
//...
}
}
EDIT 2:
I even tried to write a fairly basic service, but still the same error. Here's what I tried with:
public interface ITest
{
void CheckItOut();
}
public class Test : ITest
{
public void CheckItOut()
{
}
}
ObjectFactory.cs
kernel.Bind<ITest>().To<Test>();

Injecting Dependency into Web API Controller

I want to inject unity container into WebController.
I have UnityDependencyResolver:
public class UnityDependencyResolver : IDependencyResolver
{
readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
public void Dispose()
{
_container.Dispose();
}
}
Then, in my Global.asax I add the following line:
var container = new UnityContainer();
container.RegisterType<IService, Service>
(new PerThreadLifetimeManager()).RegisterType<IDALContext, DALContext>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Then, If I use the following in a Web Controller:
private IService _service;
public HomeController(IService srv)
{
_service = srv;
}
It works fine.
But I want to inject it into WebAPI Controller, so if I do it the same way:
private IService _service;
public ValuesController(IService srv)
{
_service = srv;
}
It does not work, it says that constructor is not defined.
Ok, I create one more constructor:
public ValuesController(){}
And in this case it uses only this constructor and never the one where I should inject unity container.
Please advise.
Add this in your WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Routes and other stuff here...
var container = IocContainer.Instance; // Or any other way to fetch your container.
config.DependencyResolver = new UnityDependencyResolver(container);
}
}
And if you want the same container you can keep it in a static variable, like so:
public static class IocContainer
{
private static readonly Lazy<IUnityContainer> Container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
return container;
});
public static IUnityContainer Instance
{
get { return Container.Value; }
}
}
More info can be found here:
http://www.asp.net/web-api/overview/advanced/dependency-injection
On a sidenote, I can also recommend the nuget-package Unity.Mvc. It adds a UnityWebActivator and support for PerRequestLifetimeManager.
https://www.nuget.org/packages/Unity.Mvc/

parameterized mvc 4 web api constructor using Ninject not working

I followed the instructions in this article to use Ninject for MVC 4 Web API Controller Constructor injection:
http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api/
the problem that i am facing is when i call the api method i get error saying "Type 'CarController' does not have a default constructor".
i have even set break points at NinjectWebCommon.CreateKernel to see if that is being called. And that does get called when application runs.
Am i missing any thing?
by the way, i installed Ninject.Web.Common and Ninject from nuget for doing this. Here is my code:
MVC WEB API Controller:
public class CarController : ApiController
{
private ICarService carService;
public CarController(ICarService carService)
{
this.carService = carService;
}
[AcceptVerbs("GET")]
public CarsResponse GetCars([FromUri] CarsRequest request)
{
return this.carService.GetCars(request);
}
}
in App_Start:
public class NinjectDependencyScope : IDependencyScope
{
IResolutionRoot resolver;
public NinjectDependencyScope(IResolutionRoot resolver)
{
this.resolver = resolver;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has been disposed");
return resolver.TryGet(serviceType);
}
public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has been disposed");
return resolver.GetAll(serviceType);
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
my NinjectWebCommon looks like this:
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();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICarService>().To<CarService>();
}
}
I was having the same issue. I found the resolution by doing the following. I lost track of the webpage where I found the class NinjectMVCDependencyResolver.
/// <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);
// Install our Ninject-based IDependencyResolver into the Web API config
GlobalConfiguration.Configuration.DependencyResolver
= new NinjectDependencyResolver(kernel);
// Install into the MVC dependency resolver
System.Web.Mvc.DependencyResolver.SetResolver(
new NinjectMVCDependencyResolver(kernel));
return kernel;
}
public class NinjectMVCDependencyResolver : NinjectDependencyScope
, System.Web.Mvc.IDependencyResolver
{
private IKernel kernel;
public NinjectMVCDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}

Using Ninject DI for both api and "regular" controllers in MVC4 [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
MVC3 + Ninject - How to?
In a small mvc 4 project, I'm trying to implement dependency injection using ninject.
So far, I have it working with api controllers, but I'm not having any luck with regular controllers.
I have A NinjectResolver:
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(_kernel.BeginBlock());
}
public override void Dispose()
{
_kernel.Dispose();
}
}
And a NinjectScope:
public class NinjectDependencyScope : IDependencyScope
{
protected IResolutionRoot ResolutionRoot;
public NinjectDependencyScope(IResolutionRoot kernel)
{
ResolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return ResolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return ResolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
var disposable = (IDisposable)ResolutionRoot;
if (disposable != null) disposable.Dispose();
ResolutionRoot = null;
}
}
Then I set it up in my Global.asax:
var kernel = new StandardKernel();
kernel.Bind(typeof(IRepository)).To(typeof(Repository));
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
Then I inject a repository into an api controller like this:
private IRepository _repository;
public TestApiController(IRepository repository)
{
_repository = repository;
}
This works fine, but doing the same in a regular controller fails with the
"No parameterless constructor defined for this object" error.
Any ideas?
ASP.NET MVC uses a different IDependencyResolver than ASP.NET WebAPi namelly Sytem.Web.Mvc.IDependencyResolver.
So you need a new NinjectDependencyResolver implementation for the MVC Controllers (luckily the MVC and WepAPi IDependencyResolver almost has the same members with the same signatures, so it's easy to implement)
public class NinjectMvcDependencyResolver : NinjectDependencyScope,
System.Web.Mvc.IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
}
And then you can register it in the Global.asax with:
DependencyResolver.SetResolver(new NinjectMvcDependencyResolver(kernel));