structuremap Property Injection - dependency-injection

How to do Dependency Injection on Property of a class Using Structure Map
public class ContactController : Controller
{
public IContactService Service { get; set; }
public ContactController()
: this(null,null)
{
}
[SetterProperty]
public MembershipProvider Provider { get; private set; }
}
Here when i Create instance of ContactController i want provider to be set to Mock<MembershipProvider> please help me how to go about doing this? Mock is Moq Framework class

If you are using a Mock, you are most likely writing test code. If thats the case, you likely don't need a dependency injection tool like StructureMap involved. Just set the Provider property manually to your MembershpProvider in your test setup code.
controller.Provider = Mock<MembershipProvider>
If you really want to configure setter injection using StructureMap, see this answer:
Property Injection into an Action Filter

Related

How Migration Works in Repository Pattern

Currently I am developing Large N-tire Application in Asp.Net MVC and
want to Separate Data,Entity,Service,Repository(Generic repository
with Unit Of works) I have reference Long Le article in Class
library project so I can reuse code in both controller and in Web API
Controller with code first entity framework and migration occurs if
model is changed.So,please suggest best approach for above
understanding?
As I have created separate project is there any effect in future while doing migration ?
You don't need repository pattern with Entity Framework Code First, because DbContext implements repository pattern and unit of work.
I usually define common database interface. Something like that:
public interface IDatabase
{
IDbSet<Plan> Plans { get; set; }
int SaveChanges();
}
Then I implement interface with my DbContext:
public class MyContext : DbContext, IDatabase
{
public IDbSet<Plan> Plans { get; set; }
// ...
}
You can create a context for testing purposes
public class MyMockContext : IDatabase
{
public IDbSet<Plan> Plans { get; set; }
// ...
}
But in your controller you always dependency-inject IDatabase. So that it's not dependent on any concrete implementation (and I use EFMock library in my tests).

NInject and MVC 3 - Should I use DependencyResolver instead of [Inject] attribute?

Recently I moved to MVC 3 and Ninject 2. In most of the code, I use constructor injection, but there are some places, where I had to use Inject attribute. Ninject 2 registers its own IDepencyResolver interface. I don't like DependencyResolver class being part of System.Web.Mvc namespace, because its function is not really strictly related to MVC, but now, when it is there, I can do
public SomeClass
{
public IUserService UserService { get; set; }
public SomeClass()
{
UserService = DependencyResolver.Current.GetService<IUserService>();
instead of
public SomeClass
{
[Inject]
public IUserService UserService { get; set; }
so I don't have to reference Ninject namespace in my classes. Should DependencyResolver be used like that?
I use property injection only for dependencies that are not required for the proper working of the class but could add some functionality if the user sets them. Example of such functionality is logging. So you could have a property which represents a logger where the user can supply his own implementation and if he doesn't the class continues to work normally but it simply doesn't log.
For everything else I use constructor injection. This way you indicate to the consumer that this class has a required dependency on some other service.
So to answer your question about the property injection I would simply have:
public SomeClass
{
public IUserService UserService { get; set; }
public void SomeMethodWhichDoesntEnforceUserService()
{
if (UserService != null)
{
// Provide some additional functionality
}
}
}
and if your class cannot function properly without the user service:
public SomeClass
{
private readonly IUserService _userService;
public SomeClass(IUserService userService)
{
_userService = userService;
}
public void SomeMethodWhichRequiresTheService()
{
_userService.DoSomething();
}
}
So in both cases no reference to any DI specifics. That's what Inversion of Control is all about.
First question I would ask is why you can not perform constructor injection of the IUserService into SomeClass? It may indicate an issue with the design.
To avoid direct reference to the DependencyResolver you could implement some form of abstraction of a Service Locator over the DI framework, e.g. CommonServiceLocator, but as the answer to this question indicates, such abstractions shouldn't be necessary when doing DI correctly. Instead you should adjust the design of the application.
I believe the ninject.web.mvc version for mvc3 now supports constructor injection on filter attributes. Have you tried it?

.NET MVC - where to use dependency injection?

I'm currently injecting dependencies into controllers using a IoC container (Castle). This is possible because you need to create a custom controller factory which enables the dependency injection.
What are other examples of dependency injection? At which point in an MVC application would you use it, and where does a 'factory' come into play?
I am using Ninject. At my project:
Service layer objects are injected into controllers (using constructor).
Repositories are injected into service layer objects (using constructor).
ObjectContext is injected into repositories (using constructor).
web.config setting are encapsulated into a class, which implements IAppSettings interface, which is then injected into service layer.
NinjectActionInvoker is injected as IActionInvoker. It takes care of injecting services into ActionFilters.
I have my own implementation of IPrincipal interface, which is injected into service layer, instead of referring to HttpContext.Current.User.
Example using Ninject:
public class UserService : GenericService<User>, IUserService
{
public ISettingService SettingService { get; set; }
public ICTEmailSender CTEmailSender { get; set; }
public ICTSettings CTSettings { get; set; }
public ICTPrincipal User { get; set; }
}
Ninject rules:
Bind<ICTPrincipal>().ToMethod(c => (ICTPrincipal)HttpContext.Current.User).OnlyIf(a => HttpContext.Current.User is ICTPrincipal);
Bind<ICTEmailSender>().To<CTEmailSender>();
Bind<ICTSettings>().To<CTSettings>();
Not only service is injected into controller, but parts of service are injected into it. It makes service more testable. I am sure it can be easily ported into Castle.

Why are there 2 constructors in the Default AccountController provided by the MVC?

here's the default AccountController.cs that's generated by the framework.
public class AccountController : Controller
{
public IFormsAuthentication FormsAuth { get; private set; }
public IMembershipService MembershipService { get; private set; }
public AccountController()
: this(null, null)
{
}
public AccountController(IFormsAuthentication formsAuth, IMembershipService membershipService)
{
FormsAuth = formsAuth ?? new FormsAuthenticationService();
MembershipService = membershipService ?? new AccountMembershipService();
//---
}
This is easy to understand.
public AccountController(IFormsAuthentication formsAuth,
IMembershipService membershipService)
{
FormsAuth = formsAuth ?? new FormsAuthenticationService();
MembershipService = membershipService ?? new AccountMembershipService();
}
What's this? What's its purpose? Is it particular to the Account Controller or is it a requirement for other controllers? and, why should I incorporate it in my project?
public AccountController()
: this(null, null)
{
}
They seem to use this type of constructors in two other places.
Thanks for helping
This is actually an implemenation of the Bastard Injection anti-pattern.
The idea is that Constructor Injection is supported to allow Dependency Injection (DI), while still providing a default constructor for default behavior.
It's really not necessary to have the default constructor, but if you omit it, you must supply a custom IControllerFactory, as the DefaultControllerFactory assumes that all Controllers have default constructors.
ASP.NET MVC is built with DI in mind, but I guess that to keep it simple, the Bastard Injection pattern was used for the project template to avoid forcing a specific IControllerFactory upon developers.
If you use a DI framework (like Unity) and you active your controllers via the container, it might not find the dependencies and use the default constructor (in this case).
If you would like use use generics, something like ... where T : IController, new() you will need a default constructor.
Another reason for having a default (no parameter) constructor is for Reflection.
The classes in the System.Reflection namespace, together with Type, allow you to obtain information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types. You can also use reflection to create type instances at run time, and to invoke and access them.
There might be times where you need to create a temporary object of that type in order to reflect over it's properties or methods, but don't want or need the overhead of creating a real object - especially if that entails accessing a database or remote service for example.

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