ninject , How to use the Ninject xml config with TEntity?


How to use the Ninject xml config with TEntity?

Question:

Tag: ninject

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 work.


Answer:

You can find out what the name of the type is by doing typeof(IRepository<>).FullName and then configure the XML as follows:

<module name="myXmlConfigurationModule">
    <bind service="MyNamespace.IRepository`1, MyAssembly"
          to="MyNamespace.Repository`1, MyAssembly" />
</module>

I haven't used the XML extensions for Ninject before, but that should work


Related:


Can I specify multiple parameters using WhenInjectedInto for ninject?


.net,dependency-injection,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 Binding Issue


c#,wcf,ninject
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


c#,xml,generics,ninject
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"/> ...

Is possible constructor injection using deserialization?


c#,serialization,ninject,inversion-of-control,ioc-container
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...

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


c#,ninject
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) {...

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


dependency-injection,ninject,inversion-of-control
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...

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


ninject
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)....

Ninject Owin Request Scope Silently Fails


dependency-injection,ninject,owin
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...

Ninject.Mvc5 does not work with mono


asp.net,asp.net-mvc,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 (3.2.0.0) does not work. After installing from NuGet, it created file NinjectWebCommon.cs have class NinjectWebCommon....

How to get implementing type during Ninject dependency resolve?


c#,ninject
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....

How to test use of DI (NInject)


.net,testing,dependency-injection,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...

Log4Net with Asp.NET MVC, entity framework and dependency injection using NInject [closed]


asp.net-mvc,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


c#,.net,model-view-controller,ninject
Hi I am following below link, http://codeclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject-dependencies-into-asp.net-mvc.aspx 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:...

Factory methods in Ninject C#


c#,ninject
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...

Ninject Decorator not being used


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;...

Ninject Singleton vs CS Singleton


c#,singleton,ninject
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...

Entity framework object not updating after being passed around


c#,entity-framework,dependency-injection,ninject,.net-4.5
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...

Webapi v1 routes are not adhered to


asp.net-mvc-4,asp.net-web-api,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...

Error getting Ninject and WebApi v1 (MVC4) to work


asp.net-mvc-4,asp.net-web-api,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...

How to use the Ninject xml config with TEntity?


ninject
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...

Ninject does not trigger method when binding to method?


c#,.net,ninject
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


c#,ninject
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...

MVC/nInject: Implementing My Own ApplicationUserManager


c#,asp.net-mvc,asp.net-mvc-4,ninject
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...

How to pass parameters down the dependency chain using Ninject


.net,c#-4.0,ninject
My Class Structure is: public class PhotoService { private IRepository _repo; private DTConfig _config; public PhotoService(IRepository repo, DTConfig config) { _repo = repo; _config = config; } } public class DTConfig { private int _accountId; public DTConfig(int accountId) { _accountId = accountId; } } My Ninject Bindings are like: var...

Domain Events without Service Location


c#,domain-driven-design,ninject,inversion-of-control
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)...

Process list of object by type


c#,ninject,web-api,nancy,onion-architecture
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...

NinjectWebCommon bindings not loading from subdirectories


c#,ninject
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...

ninject conventions multiple binding constructor injection


c#,ninject
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...

Ninject generic binding resolve throws ActivationException


c#,generics,ninject
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...

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


c#,asp.net-mvc,asp.net-web-api,ninject,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;...

IoC and Deserialization trouble


c#,serialization,inversion-of-control,ninject
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) {...

Configure Ninject Factory to return the same instance every time


c#,entity-framework,ninject,ninject-extensions
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)...

Inject object as lazy loading


c#,.net,model-view-controller,ninject,inversion-of-control
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...

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


c#,asp.net-mvc,asp.net-mvc-4,ninject
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,...

Ninject Providers -> Get another dependency inside the provider


c#,dependency-injection,ninject
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...

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


c#,asp.net,asp.net-mvc,asp.net-mvc-4,ninject
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...

Hangfire with Ninject


c#,ninject,ioc-container,hangfire
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...

How do I create Ninject bindings with multiple conditions?


c#,ninject
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.

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


c#,ninject
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...

Ninject won't resolve constructor dependencies - Web API 2


.net,ninject,asp.net-web-api2
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...

How can I create a specific object type at runtime?


c#,ninject,inversion-of-control,ioc-container
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 {...

Can I use Ninject when setting up my routes?


asp.net-mvc,asp.net-mvc-routing,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 =...

Add WebApi 2 to existing project - Ninject


c#,asp.net-mvc-4,asp.net-web-api,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 GetBindings with Interface


c#,.net,dependency-injection,ninject
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...

Ninject not injecting service into Web Forms page


c#,asp.net,asp.net-mvc,dependency-injection,ninject
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 3.2.1.0 Ninject.Web 3.2.1.0 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...

Setting up dependency injection with Caliburn Micro & Ninject


c#,wpf,dependency-injection,ninject,caliburn.micro
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...

Dependency Injection for concrete .Net classes


c#,.net,dependency-injection,ninject
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...

Ninject factory create T based on enum


c#,ninject
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...

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


c#,asp.net,asp.net-mvc,asp.net-mvc-3,ninject
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...

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


dependency-injection,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...