ninject,ninject-2,ninject.web.mvc , Ninject Decorator not being used

Ninject Decorator not being used


Tag: ninject,ninject-2,ninject.web.mvc

What I am trying to do is wrap a decorator around a command using the following code.

public interface ICommand

public interface ICommand<T> : ICommand where T : class
    void Execute(T args);

public class TransactionalCommand<T> : ICommand<T>
    where T : class
    private readonly ICommand<T> command;

    public TransactionalCommand(ICommand<T> command)
        this.command = command;

    public void Execute(T args)
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))


Here is how I am invoking the resolve but i only get back my ChangePasswordCommand without the decoratoration. (Actually it wont event compile on the second Bind)

The ultimate goal is to have this auto-register all my types using this decorator. Any help would be great!


        var command = kernel.Get<ChangePasswordCommand>();


You were pretty close. However: when you want to use a decorator you need the decorator to implement the same interface as the command. That's the case here, but you'll also need to resolve that interface (and bind it, too). So here's how it works:


var command = kernel.Get<ICommand<ChangePasswordArgs>>();


Configure Ninject Factory to return the same instance every time

I have a service layer that I am reusing (AKA Business Layer). Here's an example of one of my services with an IMyContextFactory dependency, this returns an instance of IMyContext. public class MyService : IMyService { private IMyContextFactory DbContextFactory; public MyService(IMyContextFactory dbContextFactory) { this.DbContextFactory = dbContextFactory; } public DoSomething(int id)...

How to get implementing type during Ninject dependency resolve?

I use Log4net for logging and I have a lot of objects with an ILog dependency. These dependencies are injected just as the others. I would like to stick to the Log4net logger naming convention so the logger injected to an instance is named after the type of the instance....

Setting up dependency injection with Caliburn Micro & Ninject

I'm trying to set up dependency injection in a new WPF project using the framework Caliburn Micro and Ninject. Unfortunately I'm not succeeding :( There are a few examples on the internet which implement a generic Bootstrap but for me the generic Bootstrap class is not available and since all...

Ninject GetBindings with Interface

I'm trying to set up by Ninject kernel like so: kernel.Bind<IPersist<SomeDataItem>>().To<SomeDataRepo>(); kernel.Bind<IPersist<AnotherItem>>().To<AnotherRepo>(); So that when my service recieves an instance of SomeDataItem - I find the appropriate repository / store to persist it: kernel.GetBindings(typeof(IPersist<>)) .Where(binding => binding.Service.GenericTypeArguments[0] == typeof(SomeDataItem)) However - I cannot get this to work. If I set...

Domain Events without Service Location

Giving the default implementation of Domain Events: Interface that represents an domain event: public interface IDomainEvent { } Interface that represents a generic domain event handler: public interface IEventHandler<T> where T : IDomainEvent Central access point to raise new events: public static class DomainEvents { public static void Raise<T>(T event)...

NinjectWebCommon bindings not loading from subdirectories

I have an MVC project that loads plugins from a configured folder using ninject. It has been working just fine for months, but the project requirements have changed. The plugins now need to be in separate folders to allow easier clean-up of dependent libraries or other files. This code is...

How do I create Ninject bindings with multiple conditions?

Is it possible to create bindings by combining conditions? For eg combining .WhenInjectedExactlyInto and WhenParentNamed ? Typically I end up using the When syntax and incorporating the Ninject source code for those methods but I'm wondering if there's a generic way to do this.

Ninject always injects null HttpContext.Current() [duplicate]

This question already has an answer here: MVC5 Ninject binding and HttpContext 3 answers I am attempting to inject a UserFactory via Ninject, here is my binding: var u = new CurrentUserProvider(HttpContext.Current); kernel.Bind<ICurrentUserProvider>().ToMethod(context => u).InRequestScope(); This factory uses HttpContext to read a authentication cookie and populate a CurrentUser object,...

IoC and Deserialization trouble

I am using Ninject for IoC. UPDATE My repository uses XML Serializer to persist objects. How do I inject dependencies after deserializing an entity with behavior and state in the same class (POCO) and without using the service locator anti-pattern? This is the Save method: public void Save(IIntegrationService service) {...

Ninject won't resolve constructor dependencies - Web API 2

I've removed Unity and am now attempting to use Ninject in its place. For the most part it works, however I cannot get it to play nice with Web API 2. I have a NinjectWebCommon.cs file (which I have not changed aside from adding some registrations which work fine if...

Ninject does not trigger method when binding to method?

The ViewModel depends on a list of MyObject which is bound to a Repository method that looks like it never gets called? CompositionRoot public sealed class CompositionRoot { public CompositionRoot(IKernel kernel) { if (kernel == null) throw new ArgumentNullException("kernel"); this.kernel = kernel; } public void ComposeObjectGraph() { BindRepositoriesByConvention(); BindDomainModel(); }...

Check if a lazy singleton was ever created

Using ninject, I have a binding like this: kernel.Bind<IFoo>().To<MyFoo>().InSingletonScope() .WithConstructorArgument("bar", new Action<IFoo>(foo => { // some function here })); What I want to be able to do is determine whether or not IFoo was constructed without actually trying to use it (since that would cause it to be constructed). Is...

How to use NinjectModule with Ninject.MVC and multiple layers?

I have four layers in my application where the Service layer is the context root: Presention | | Services (Context Root) | | Repository | | Data I am using Ninject MVC for the Presention layer specific items, and I have everything else registered in the services layer (context root)....

Log4Net with Asp.NET MVC, entity framework and dependency injection using NInject [closed],entity-framework,dependency-injection,ninject,log4net
Just started with Log4Net, read the tutorial and got up with a simple console application. But I am wondering how to get started with MVC and entity framework code first with dependency Injection using NInject. Can some one please give some pointers?

Ninject 1.0 to 2.0 .Only

Hi I am following below link, I get error on line: kernel.Bind<IHttpController>().To<MyTESTController>() .Only(When.Context.Variable("controllerName") .EqualTo("CorporateRequirementsController")) .InjectPropertiesWhere(p => p.Name == "ActionInvoker"); I believe .Only is the syntax from Ninject 1.0, what is the equivalent in 2.0? The error I am getting is like this:...

How to handle layer specific Dependency Injection in a reusable dll with ninject?

We use ninject as our DI solution. How do I create a self sustaining class library dll with its own internal IOC. Basically I have created a service that does something and I want to register the bindings in the dll and just hand it to other people. I don't...

How to use the Ninject xml config with TEntity?

This should work:- Bind(typeof(IRepository<>)).To(typeof(Repository<>)); where:- IRepository<> is an interface of the form:- public interface IRepository<T> where T :class { //... } Repository<> is a class of the form:- public class Repository<T>:IRepository<T> where T :class { //... } But how to do it in XML configuration using Ninject.Extensions.Xml? It does not...

How do I add Ninject Controller Factory to an ASP.NET MVC app with OWIN?

I'm developing an ASP.NET Web Api 2.2 project with Visual Studio 2012 Premium, .NET Framework 4.5.1 and C#. I have created an empty ASP.NET MVC 5 project. I have deleted Global.asax and create this Startup.cs class: using Microsoft.Owin; using Ninject; using Ninject.Web.Common.OwinHost; using Ninject.Web.WebApi.OwinHost; using Owin; using System.Reflection; using System.Web.Http;...

Error getting Ninject and WebApi v1 (MVC4) to work,,architecture,dependency-injection,ninject
This is the error message I get: "Type 'GDMServices.Controllers.DmpeController' does not have a default constructor", I started going down this path as the answer appeared to work for a couple of users but I started getting errors that made me think something has changed and abandoned that solution. One of...

Is possible constructor injection using deserialization?

On the following code: var serializer = new XmlSerializer(typeof(MyPOCOType)); using (var reader = XmlReader.Create(fileName)) { var pocoInstance = (MyPOCOType)serializer.Deserialize(reader); } I am using ninject. The MyPOCOType has an dependency that is passed by constructor injection. The instance of MyPOCOType is being created by the Deserialize method, so the dependencies are...

Ninject Providers -> Get another dependency inside the provider

I'm wondering what the best practices is here. I need to construct a DbContext for my multi tenanted application, so I have made a Dependency provider like this: public class TenantContextFactoryProvider : Provider<DbContext> { protected override DbContext CreateInstance(IContext context) { var tenant = // How to get the tenant through...

Ninject Decorator not being used

What I am trying to do is wrap a decorator around a command using the following code. public interface ICommand { } public interface ICommand<T> : ICommand where T : class { void Execute(T args); } public class TransactionalCommand<T> : ICommand<T> where T : class { private readonly ICommand<T> command;...

Factory methods in Ninject C#

I have an interface called IBreakfastProvider, which has several implementations. Currently my code decides which one to use based off an id. It uses a factory method, like this: public IBreakfastProvider GetBreakfastProvider(int id) { switch (id) { case 1: return new CornFlakeProvider(new SomeDependency()); case 2: return new MuesliProvider(new SomeOtherDependency()); case...

How do I bind generic types with inheritance using custom logic?

I have a generic interface IService which is concretely implemented by three or four implementations. public interface IService { void HandleRequest( RequestData data ); } public class AService : IService { public void HandleRequest( RequestData data ) { } } public class BService : IService { public void HandleRequest( RequestData...

I'm using ninject 3.0 and mvc 3. I get the error rror activating IProductRepository

I am new to MVC so im fallowing a book example. But when I run the program it gives me the error: Error activating IProductRepository No matching bindings are available, and the type is not self-bindable. Activation path... I have read a bunch of articles and other error like this...

Ninject Singleton vs CS Singleton

Can someone please tell me the difference between a C# Singleton Class and a Ninject Singleton? My current boss would like to convert a Singleton class into a Ninject Singleton. This goes against methodology for me that I would have Ninject define the singleton rather than the class itself define...

How can I force Ninject to exception when largest constructor has unresolvable dependencies?

According to the documentation for Ninject: The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:- If a constructor has an [Inject] attribute, it is used (but if you...

How can I create a specific object type at runtime?

I have an interface that is implemented by all of my classes which are responsible for exporting data to different formats. Sample code: public interface IExport { string Exporter(); } public class ExcelExport : IExport { public string Exporter() { return "excel"; } } public class PdfExport : IExport {...

Webapi v1 routes are not adhered to,,ninject
The webapi call returns the error: message: "No HTTP resource was found that matches the request URI 'http://localhost:25396/api/dmpe/form/123'.", messageDetail: "No action was found on the controller 'Dmpe' that matches the request." Controller: [HttpGet] [ActionName("GetForm")] public HttpResponseMessage GetForm(long formId) { try { var form = this.dmpeService.GetForm(formId); return Request.CreateResponse(HttpStatusCode.OK, form); } catch...

Inject object as lazy loading

I have MVC code like below. I use nInject for IoC. I wonder when I push request to do for example SendMail there is create controller object, nInject create subobjects for both readonly objects: _mailSrv and _dbSrv, but I need in this request only one variable. Is it possible to...

How to test use of DI (NInject)

I have an ASP.NET MVC app that has a NInject container for dependency injection. As advertised, IoC makes it pretty easy for me to test components in isolation, and then easy to compose components in the application. I want to test my use of the DI. I don't want to...

ninject conventions multiple binding constructor injection

so I'm having an issue with getting all instances of classes that implement a generic interface to come through in my constructor I am using kernel.Bind(x => x.FromThisAssembly().SelectAllClasses() .InheritedFrom(typeof(IRepository<>)).BindAllInterfaces()); I have a test that passes when I ask for a specific repository var booking = kernel.Get<BookingRepository>(); Assert.IsNotNull(booking); but I have...

ASP.Net MVC4 using Ninject, HttpPost returns 'No parameterless constructor'

Here's my situation: I have a very simple MVC4 application. One view, one controller, limited responsibility. It functions as a landing page for a vendor application, and is responsible for: Reading ActiveDirectory properties of the user Reading membership of that user from the vendor application's db If membership for the...

Can I use Ninject when setting up my routes?,,ninject,ninject.web.mvc
I have an ASP.NET MVC5 web site that uses Ninject. The site is for an online magazine. What I would like to do is set up some routes, but pull the data from an injected repository. So, I would like to have routes like these... routes.MapRoute("Section9", "Section9_Ask-the-professional", new {controller =...

MVC/nInject: Implementing My Own ApplicationUserManager

I'm using nInject in an MVC4 app. I would like to implement my own version of ApplicationUserManager because the scaffolded one creates a separate instance of my database context (I use nInject to inject a request scope database context into my controllers). Having a separate database context in ApplicationUserManager is...

Ninject Owin Request Scope Silently Fails

The problem - Ninject kernel is always returning new instances even if they are scoped to the request. -I'm using OWIN with the SystemWeb host package to allow me to use IIS. -The project depends on an API app that has all the necessary Ninject/owin libraries installed. app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(config); -Everything worked...

Add WebApi 2 to existing project - Ninject

I have existing project ASP.NET MVC 4. I want to add to the project WebApi2. So I install WebApi2 in Nuget and create ApiController. When I running project then I got a error The IControllerFactory 'MvcApplication.Infrastructure.NinjectControllerFactory' did not return a controller for the name 'api'. My NinjectControllerFactory: public class NinjectControllerFactory...

Ninject generic binding resolve throws ActivationException

I have a generic type for query handlers. public interface IQueryHandler<in TQuery, out TResult> where TQuery : IQuery<TResult> { TResult Execute(TQuery query); } And I have so many implementation for this interface. So I created a service to resolve these types: public class QueryService : IQueryService { private readonly IResolver...

Is it a good practice to pass the Ninject kernel around?

I'm writing a small framework that executed a couple of tasks. Some om the tasks needs specific properties which are injected through Ninject. Let's say that I have the following constructor in my base class that represents a single Task: protected DDPSchedulerTask(ILogger logger, List<string> platforms, IBackOfficeDataStore backOfficeDataStore, ICommonDataStore commonDataStore) {...

Ninject not injecting service into Web Forms page

I've trying to use Ninject for DI in a combined ASP.NET Web Forms and MVC project. I installed the following packages (and their dependencies) via NuGet: Ninject.MVC5 Ninject.Web In ~/App_Start/NinjectWebCommon.cs I register services: private static void RegisterServices(IKernel kernel) { kernel.Bind<ITermusRepository>().To<TermusOracleRepository>(); } In MVC controllers, I use constructor injection...

Dependency Injection for concrete .Net classes

What is the preferred way for injecting/isolating classes that are sealed in dlls and do not implement interfaces? We use Ninject. Let's say that we have a class "Server" and we want to inject/isolate the class TcpServer which "Server" uses. Don't want to be too specific because I want to...

Can I specify multiple parameters using WhenInjectedInto for ninject?

When setting up my ninject bindings, I'm using the .ToMethod to specify particular parameters for specific connectionstrings, and the WhenInjectedInto method to constrain the binding to specific types: Bind(Of IDbConnection).ToMethod(Function(context) New OracleConnection(ConnectionStringFactory.GetConnection(DBC.ConnectionStrings.Oracle))).WhenInjectedInto(Of AccountBalancesLookup)() Bind(Of IDbConnection).ToMethod(Function(context) New...

Ninject.Mvc5 does not work with mono,,mono,ninject,ninject.web.mvc
Am following video tutorial from you-tube for making web app with ASP.Net. The guy teaching there is using Windows and Visual Studio. I'm on Ubuntu 14.04 and Monodevelop. Everything is set and running but Ninject ( does not work. After installing from NuGet, it created file NinjectWebCommon.cs have class NinjectWebCommon....

Ninject Binding Issue

I have a wcf service application and I have just implemented ninject library. In ninject web site there is following example: public class Samurai { public IWeapon Weapon { get; private set; } public Samurai(IWeapon weapon) { this.Weapon = weapon; } } public class WarriorModule : NinjectModule { public override...

Ninject generic type xml binding

I need to bind generic interface with generic implementation using Ninject.Extensions.Xml. The project is .net mvc project. Is there any way to accomplish this ? The class: public class JsonProvider<T> : IJsonProvider<T> where T: new() { ... } Xml configuration (Not working): <bind service="Base.IJsonProvider, Base" to="Base.JsonProvider, Base" name ="Config"/> ...

Hangfire with Ninject

I am attempting to use Hangfire with Ninject. Here's my problem, my project is layed out like the following: .Sln |- Core |- Web Now in the Core is the Hangfire method: public class Scheduler { public void HangfireIoc() { BackgroundJob.Enqueue<MovieSaver>(x => x.SaveMovies()); } } MovieSaver class in (Core): public...

Entity framework object not updating after being passed around

I'm working on setting up a new MVC payment site with a dependency-injected database connection in a separate project, and experimenting with some new things as I do. Currently, I'm trying to load an existing transaction from the database, authorize the card payment, and then save the result back to...

Ninject factory create T based on enum

I want to let Ninject resolve an instance of T based on a specific enum input value. I have read about Ninject's factory extension, but I couldn't find any example having the factory resolve a specific class based on an enum. Each class derives from a base class and that...

Process list of object by type

I have a requirement to create a Sync method. 1) On input it takes SyncRequest object. class SyncRequest{ public List<SyncObj> Objects{get;set;} } class SyncObj{ public Type Type{get;set;} public object Object{get;set;} } 2) Based on type of each object i need to use different service to proceed and the different repository...