ASP.NET MVC Views Dependency Injection without DependencyResolver? - asp.net-mvc-3

Is it possible to inject dependencies into an MVC ViewPage (must support layout pages) without using DependencyResolver?
I would rather not use DependencyResolver at all (I had major problems when injecting NH sessions into ActionFilters in the past (leaking all over the place)). However, I'm not sure if there is an alternative?
The other complexity I have is that the DependencyResolver needs to be tenant aware (each tenant has its own (StructureMap) container). I'm currently doing this by passing in a lazy instance of my tenant container resolver (seems this is necessary otherwise the resolver is cached):
public SmDependencyResolver(Func<ISiteContainerResolver> containerResolver)
{
this.containerResolver = containerResolver;
}
public object GetService(Type serviceType)
{
var container = containerResolver().Resolve();
If I end up using DependencyResolver should I ditch my StructureMap controller factory since it looks like DependencyResolver handles this too?
Thanks
Ben

Given that the DependencyResolver is used by so many aspects of the ASP.NET MVC framework for dependency injection your life will be easier if you use it - as you say it means you don't need your own versions of things like the controller factory.
That said, the framework is very flexible and it is always open for you to plug in your own version of things - I just prefer to create as little of my own code as possible on the KISS principle.

Related

What is alternate for CreatePerOwinContext in .net core 2.1

I had a webapi in which I was using app.CreatePerOwinContext in startup.cs file but I want to migrate that webapi to .net core 2.1. So I have stuck at this point as I can't fine any alternate for CreatePerOwinContext.
Here is my webapi code:
public static UserManager<IdentityUser> Create(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
{
var manager = new UserManager<IdentityUser>(new UserStore());
return manager;
}
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<UserManager<IdentityUser>>(Create);
...
}
So how can I convert the above code in .net core 2.1?
That method was used as a service locator to load up dependencies and then access them throughout your code. Service location on its own is considered an anti-pattern, and is not recommended for use in the vast majority of real world situations.
Instead, people use IOC containers now to manage their dependency injection. In ASP.NET MVC Core, there's now a lightweight and "good enough" IOC container provided for you as part of the framework.
Microsoft provides an overview in this article, but the short version is that in your Startup.cs you register your dependency tree under ConfigureServices (usually using an extension method so Startup.cs doesn't get too large).
After you've registered your dependencies, you load them either through property injection, constructor injection, or method parameter injection. This results in cleaner code that is more maintainable than standard service location.
Edit:
If you truly insist on managing a service locator either because the technical debt is acceptable or because the business case warrants the current design, then I suggest you transition your work from OwinContext over to HttpContext.
In ASP.NET Core, you access the HttpContext by injecting the HttpContextAccessor into your class, and changing your OwinContext calls to pull from the key value store in HttpContext.
Instructions for injecting HttpContextAccessor can be found in this SO answer. Simply store KVPs using HttpContext.Current.Application["myObject"].
I don't recommend doing this, but I'm willing to share it because I understand the reality of deadlines vs the idealism of architecture.

Sample IoC, that is not DI

Dependency Injection is some form of Inversion of Control.
Could somebody please specify some other form of Inversion of
Control, that is not a dependency injection ?
Is there any java framework that is IoC container, but is not a DI
container ?
Which part of spring is IoC, but not a DI ?
Inversion of Control is the ability to allow a framework to run your custom code. As Martin Fowler says here:
Inversion of Control is a common phenomenon that you come across when
extending frameworks. Indeed it's often seen as a defining
characteristic of a framework.
So this is an example of Inversion of Control:
public class HomePage : Page
{
protected override void OnPageLoad(object sender, EventArgs e) {
// here your custom code
}
}
Here we have some custom class that 'by some convention' the framework (ASP.NET Web Forms in this case) picks up and it runs our custom code. The way it is done here is by inheritance and overriding virtual methods of the base class that the framework provides.
So this is an other example of Inversion of Control:
public class HomeController : Controller
{
public ActionResult Save(HomeSaveModel model) {
// here your custom code
}
}
Here we have our own custom controller where again the framework will call our code by some convention. Here we still use a base class given by the framework, but now the framework will call our Save action using reflection.
Inversion of control is all about hooking into framework code. Do note that in the examples above there is no dependency injection what so ever (nor is there Service Location).
Is there any java framework that is IoC container, but is not a DI container ?
The name "IoC container" is misleading, because those tools are meant to help you wire the dependency graphs in your application and do not help you wiring your code to a framework. IoC is a property of a framework; if it doesn't do IoC, it's not a framework: it's a library. Therefore "IoC containers" are libraries, not frameworks and they usually have no relationship with frameworks that we use (such as web frameworks such as ASP.NET).
So in this sense, there is no such thing as an "IoC container", since this is something that they can't do; by definition. In that context, your question stopped making sense :-), but to still answer it: no, "IoC containers" are always "DI containers" but never "IoC containers".

MVC 3 And MEF and adding plug-ins to main application

I am a newbie to MEF and I am really mixed up! There are lot of useful articles out there and neat question and answers here in stackoverflow. I downloaded the example which #matthew-abbott has uploaded in his blog , but I dont know how to add new plug-ins or extension to extend the main web application, I mean like what you can see here.
Edited :
Also I use Entity Framework, Code First Approach and Unit of work for my data access layer application, what If my plug-ins needs data access and (I mean the plug-in has itself models) wants to use the DAL I created ? As you know every time the model changes, DbContext throws and error and tells re-create DB, Is there any way or other ORM which accepts extending DAL dynamically?
That particular example shows how we can integrate MEF with MVC3's new DependencyResolver which provides a service location mechanism for various extension points within the MVC architecture. There are a few other articles on my blog which detail more information about how a possible plugin architecture could work, these are available at:
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three
There are also a host of fantastic articles, my recommendations would be to also read:
ASP.NET MVC and the Managed Extensibility Framework (MEF) by Maarten Balliauw
Defining Web-scoped parts with MEF by Tim Roberts
MVC is a very flexible architecture, there are a myriad of ways it can be extended, but because of the nature of how ASP.NET applications run in IIS, you need to consider part lifetime very carefully. As an example, controllers can only be used for one request, so you could would need to ensure that your controllers have a specific CreationPolicy. Tim Robert's article on Web-scoped parts is a particularly good read.
Hope that is enough to point you in the right direction.
Edit: Because of the modular nature that MEF provides, it is important to ensure that your different layers are decoupled. You've specified that you are using Entity Framework, but the reality is, EF should likely only be used in your data layer. Typically the MVC architecture would promote view models over domain models. To that end, it is probably useful to use something similar to the repository pattern to define, e.g. here is a mock UserRepository:
[Export(typeof(IUserRepository))]
public class UserRepository : IUserRepository
{
public IEnumerable<UserViewModel> GetUsers()
{
// Get values here from EF as domain models
// And return them as view models?
}
}
Which we can export and inject into a controller:
[ExportController("User"), PartCreationPolicy(CreationPolicy.NonShared)]
public class UserController : Controller
{
private readonly IUserRepository _repo;
[ImportingConstructor]
public UserController(IUserRepository repo)
{
if (repo == null)
throw new ArgumentNullException("repo");
_repo = repo;
}
public ActionResult Index()
{
var users = _repo.GetUsers();
return View(users);
}
}
This is just a really simple example, but like many IoC containers, MEF also supports dependency injection. As long as a part provides a suitable export, it can be imported (either through property injection, or constructor injection) into another part at composition time.
My recommendation would be against exposing EF to your views, as this makes them explicitly dependent on it. By taking care to decouple and only expose the right types at the right layers, you architecture will become a lot more robust, flexible and testable, which makes maintaining it, and updating it a lot easier. As another quick example, here is how we could test our controller:
[Test]
public void UserController_CreatesViewResult_WithListOfUsers()
{
var mock = new Mock<IUserRepository>();
mock.Setup(m => m.GetUsers()).Returns(new[] { new UserViewModel { Name = "Matt" } });
var controller = new UserController(mock.Object);
var result = controller.Index();
Assert.That(result is ViewResult);
// Other assertions.
}
Because I haven't tightly coupled EF to my view, my controller is a lot more testable, I can mock a suitable repository and test where I need to.
The important thing is planning your architecture.

Should (and if so how should) a database context be dependency injected into a controller?

It seems like at least 90+% of the Controller Actions I am writing will need to access the database. To me it seems like a logical step to have the database context automatically injected.
I have never used dependency injection before so I want to confirm this is something that is a pattern. If it is, how should I go about doing this? I know ASP.NET MVC 3 has "improved dependency injection" support, but do I still need an external framework? If so what is the default and how do I configure it to create a new database context per http request?
ASP.NET MVC 3 doesn't have improved DI support - it has improved support for the Service Locator anti-pattern (go figure). Fortunately it has had support for DI since MVC 1 through the IControllerFactory interface.
To answer the question, however, yes, it sounds like a perfectly normal thing to inject a Repository into a Controller (although normally we would slide a Domain Model in between the two).
This is best done with Constructor Injection like this:
public class MyController
{
private readonly IMyRepository repository;
public MyController(IMyRepository repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
this.repository = repository;
}
public ViewResult MyAction(int barId)
{
var bar = this.repository.SelectBar(barId);
return this.View(bar);
}
}
You'll need to provide a custom IControllerFactory to enable Constructor Injection with the MVC framework - the easiest thing is to derive from DefaultControllerFactory.
Once you have a custom IControllerFactory, you can register it in Global.asax like this:
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

Difference between use of a controller factory and NinjectHttpApplication?

Using Ninject 2 MVC 3. Correct me if i am wrong but ive seen two way of using Ninject in an MVC 3 application. We can use a new controller factory which is like ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); or using NinjectHttpApplication and then configure the kernel.
I was wondering what difference between use of a controller factory and NinjectHttpApplication to configure the binding for DI?
And what are the best place to setup DI ?
NinjectHttpApplication calls ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()) internally.
But additionally it sets up various bindings and provides many new features. In other words it's less work and adds new features. Best you read my blog post about the MVC3 extension. http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/

Resources