How to inject class in nonController class with ninject - asp.net-mvc

I set up "Ninject" in my asp.mvc project. And it works fine each controller get its dependency classes. But I have one class in mvc project that is not controller. It's a simple class that extends "MembershipProvider" (because I have made custom membership) and I need to inject "UserRepository" class in it.
In a NinjectControlelrFactory I bint it:
private void AddBindings()
{
ninjectKernel.Bind<IUserRepository>().To<UserRepository>().WithConstructorArgument(
"connectionString", ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
}
But how to get it from non controller class?
PS
I can't inject through constructor.
I have some solution but I don't know how 'clean' it is:
using (IKernel kernel = new StandardKernel())
{
kernel.Bind<IUserRepository>()
.To<UserRepository>()
.WithConstructorArgument("connectionString", "ttttttttttttt");
//var tc = kernel.Get<IUserRepository>();
this.userRepository = kernel.Get<IUserRepository>();
}

Use Property Injection. Register your MembershipProvider in the Ninject and use Property injection.
You will need to instantiate MembershipProvider via ninject context.
Check these articles.
Property Injection in ASP.NET MVC with Ninject
Injecting properties in Ninject 2 without 'Inject' attribute

Related

Implementation of DI in Asp.net Core

This issue is different, I know what DI is, but I want to know how asp.net core use DI. We can configure custom logging in ASP.NET Core, but I do not know why it works.
Normally, we use the new keyword to instantiate a class, and then we can use it in the controller. In ASP.NET Core, we use a controller constructor with parameter like below:
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
}
I know it is a design pattern called Dependency Injection, but I am wondering how this is implemented. How did the ASP.NET Core team realize this?
In Dependency Injection and Inversion of Control jargon, what is injected is called a "service".
You register your services with an IoC container upon application startup, meaning: you tie concrete implementations and a lifetime to a certain type.
Now when a controller is required to serve an incoming request, MVC will use a controller factory to look up and instantiate the relevant controller. When that controller has constructor parameters, it'll ask the IoC container to resolve the required service parameters.
More information on learn.microsoft.com: Dependency injection into controllers.

Dependency injection with Global.asax

I am using dependency injection for the inject interface with the classes
I use it in the Global.asax like this
new UnityContainer().RegisterType<IBookingService, BookingService>()
and controller
IBookingService bookingService
Now the thing is I want to change the injected implementation class for an interface in the controller level
How can I do it with a controller level?
i want to do some things like this in controller level
private readonly IBookingService bookingService;
if(countryCode = SE ){
bookingService = new bookingSE();
}
else IF (countryCode = NO ){
bookingService = new bookingNO();
}
i want to use Dependency injection for this
Make sure that you use the Unity.Mvc NuGet package. This will add a App_Start\UnityConfig.cs file to your project and you can add the registrations in its RegisterTypes method as follows:
container.RegisterType<IBookingService, BookingService>();
Perhaps you are already doing this, but I wanted to make sure since your exact code example with the new UnityContainer().RegisterType will not work.
Another interesting thing that this package does can be viewed in the App_Start\UnityWebActivator.cs file:
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
This line will register the unity container as standard MVC DependencyResolver. This allows constructor injection to be applied to your controllers. With this you can define your controller as follows:
public class MyCoolController : Controller
{
private readonly IBookingService bookingService;
public MyCoolController(IBookingService bookingService)
{
this.bookingService = bookingService
}
public ActionResult Index()
{
// your usual MVC stuff here.
}
}
In almost all cases, the use of constructor injection is advised over all forms of injection so stick with constructor injection unless there is no other way. And if you think there's no other way, please to ask here at Stackoverflow. We might be able to give some feedback on your code and design.
Just call Resolve
var bookingService= container.Resolve<IBookingService>()

IDependencyResolver in asp.net mvc

I read a bout IDependencyResolver in MVC (fundamentalbook), but i don't know what is exactly DependencyResolver in mvc?
Could some one please explain these methods?
It allows for implementing dependency injection into controllers and other components. Brad Wilson wrote a nice article about it. For example when you implement a custom dependency resolver that is capable of returning proper implementations for a give type you could have your ASP.NET MVC controllers take abstract dependencies or interfaces as constructor arguments:
public class HomeController: Controller
{
private readonly ISomeService _someService;
public class HomeController(ISomeService someService)
{
_someService = someService;
}
... some actions
}
if you have written a custom dependency resolve it will be able to inject the proper implementation of the interface when instantiating the controller.
Dependency Injection allows for weaker coupling between the different layers of your application and making them easier to unit test in isolation.

Using Ninject with Membership.Provider

I'm new to Ninject and I'm having problems using it with a custom membership provider.
My membership provider has a repository interface passed in. It looks like:
public class CustomMembershipProvider : MembershipProvider
{
public CustomMembershipProvider( IRepository repository )
{
}
}
I'm using the code thats part of the Account Model in the MVC app as a starting point.
However when it calls Membership.Provider I get an error saying No parameterless constructor defined for this object.
I've setup the bindings in ninject to bind a IRepository to a Repository class which work as I've testing this in a controller.
What are the correct bindings in Ninject to use for Membership.Provider?
This is how it should be done today with new versions of both MVC and Ninject (version 3):
You have access to the DependencyResolver instance and Ninject sets itself as the current DependencyResolver. That way you don't need hacks to get access to the static Ninject kernel. Please note, my example uses my own IUserService repository for Membership...
IUserService _userService = DependencyResolver.Current.GetService<IUserService>();
The best solution I found was the following:
private IRepository _repository;
[Inject]
public IRepository Repository
{
get { return _repository; }
set { _repository= value; }
}
public CustomMembershipProvider()
{
NinjectHelper.Kernel.Inject(this);
}
Where NinjectHelper is a static helper class to get the Kernal from.
Since the membership collection and the Membership.Provider instance are created before Ninject can instantiate them, you need to perform post creation activation on the object. If you mark your dependencies with [Inject] for your properties in your provider class, you can call kernel.Inject(Membership.Provider) - this will assign all dependencies to your properties.
I haven't used Ninject ever.
but in StructureMap i set this dependency:
expression.For<MembershipProvider>().Add(System.Web.Security.Membership.Provider);
and it works fine.

Constructor Dependency Injection in a ASP.NET MVC Controller

Consider:
public class HomeController : Controller
{
private IDependency dependency;
public HomeController(IDependency dependency)
{
this.dependency = dependency;
}
}
And the fact that Controllers in ASP.NET MVC must have one empty default constructor is there any way other than defining an empty (and useless in my opinion) constructor for DI?
If you want to have parameterless constructors you have to define a custom controller factory. Phil Haack has a great blog post about the subject.
If you don't want to roll your own controller factory you can get them pre-made in the ASP.NET MVC Contrib project at codeplex/github.
You don't have to have the empty constructor if you setup a custom ControllerFactory to use a dependency injection framework like Ninject, AutoFac, Castle Windsor, and etc. Most of these have code for a CustomControllerFactory to use their container that you can reuse.
The problem is, the default controller factory doesn't know how to pass the dependency in. If you don't want to use a framework mentioned above, you can do what is called poor man's dependency injection:
public class HomeController : Controller
{
private IDependency iDependency;
public HomeController() : this(new Dependency())
{
}
public HomeController(IDependency iDependency)
{
this.iDependency = iDependency;
}
}
Take a look at MVCContrib http://mvccontrib.github.com/MvcContrib/. They have controller factories for a number of DI containers. Windsor, Structure map etc.
You can inject your dependency by Property for example see: Injection by Property
Using Ninject looks like this:
[Inject]
public IDependency YourDependency { get; set; }

Resources