StructureMap and MVC 3.0 - asp.net-mvc

Has anyone used structuremap with the new DI features of asp.net mvc 3.0? If so, could you post some example code or some links to examples that have been helpful? In attempting to learn ASP.NET MVC 3, I am trying to make sure I use all the "new" features and am struggling with integrating a IoC container.

As others mentioned you'd want to look at Common Service Locator (CSL) that is a simple service resolution facade around any container (any of your choice).
MVC3 internally heavily uses the new IDependencyResolver interface which is somewhat like CSL but in ASP.NET MVC context. The good thing is that if you are already using CSL then you can set it as Dependency Resolver for MVC.
This topic is equally essential for any container and not specific to StructureMap.
So what is going on there:
You provide all necessary container registrations (preferrably through Registry DSL in case of StructureMap);
You get the StructureMap adapter for Common Service Locator;
You (optionally - if you need CSL along with DependencyResolver) register your StructureMap adapter as current Service Locator:
ServiceLocator.SetLocatorProvider(() => yourStructureMapAdapter)
You register your CSL (backed by StructureMap) as MVC DependencyResolver:
DependencyResolver.SetResolver(yourStructureMapAdapter)
MVC3 automatically wires everything up through IDependencyResolver interface internally (using all StrucutreMap DI auto-wiring capabilities).
Along with MVC3 baked-in IoC capabilities, use the power of IoC tool at your disposal (e.g. use Assemblies scanning available in StructureMap) to max extent.

Ran into this the other day, may be helpful:
http://weblogs.asp.net/rashid/archive/2009/02/15/asp-net-mvc-unity-and-common-service-locator.aspx

I looked around a bit and this is the first Google result I got. It gives a good of what is new in MVC 3 service location: http://bradwilson.typepad.com/blog/2010/07/service-location-pt1-introduction.html
While it is dependent on a beta version of MVC 3, I am sure with some experimentation one can figure it out.
In a nutshell, it looks like they added some interfaces and extension methods that you can use to call StructureMap, or whatever your preferred IoC library is.
Update:
I just happened upon this link in the blogs I subscribe to. It has some good-looking sample code.
http://stevesmithblog.com/blog/how-do-i-use-structuremap-with-asp-net-mvc-3/

Related

Dependency Injection in .net core, Autofac vs StructureMap vs Factory Method to resolve interface if registered with multiple implementation

In my project I using chain of responsibility designing pattern for which I need to create multiple handlers which will implement same interface. In .net application(not .net core) I would have used DI using UnityContainer where I could have resolved handlers using named parameter. But in .net core I can not do that. Now I have few options to use other DI libraries like Autofac, Structuremap or create factory method which can give me objects based on name passed. Please help me in picking right approach between these or suggest something better if available. I have not used Autofac or Structuremap so I very little idea of same. Thanks.
For the most part, all DI tools out there achieve the same thing with different APIs. These days the differences are highlighted by your needs.
StructureMap or Autofac are both good candidates. It all boils down to "flavor".
Check this article. I think is a good one. Configuration comparison dependency injection containers
Again, don't stress over them unless you need a very very specific feature form one of them.
I would do Autofac just because I haven't had the need for something else however, I would not hesitate to use StructureMap, Ninject or whatever new kid on the block is brought up.

Need architectural solution - Ninject Interception only works on classes in the kernel

I am working in an asp.net mvc application that uses Ninject for DI. I have been attempting to implement Ninject Interception for logging, following this 2-part article. http://codepyre.com/2010/03/using-ninject-extensions-interception-part-1-the-basics/. I have tried both the method registration and attribute approaches, but neither approach will let me intercept methods on classes that aren't registered in the kernel.
The problem is that mine is a multi-tenant system where I often have to do different concrete operations depending on the client who is logged in. I execute the correct functionality using the Factory Pattern to give me the right class for each client as needed. However, the classes served up by the Factory are not in the kernel and therefore cannot be intercepted.
I'm looking for any sort of solution to this problem including an architectural rework if necessary, so that I can make everything Interceptable.
What you probably are looking for is aspect oriented programming (AOP) libraries.
Look at this question: What Aspect-Oriented Programming (AOP) libraries for .NET are still actively developed?

Configuring MassTransit in Onion Architecture with ASP.NET MVC and Ninject

I am currently setting up a simple MVC application that is structured as an Onion Architecture. For simplicity's sake, assume that I have the following projects (disregarding the business and database layers, at the moment):
Sample.Web - This is the ASP.NET MVC Application
Sample.Application - This contains the application services.
Sample.Infrastructure - This contains the infrastructure services.
For now, I am using Ninject (although that will likely change). So, with Ninject MVC, I am registering the Application and Infrastructure services at startup, using the Sample.Web to act as the composition root. Application services from Sample.Application are injected into the controllers, and that is straightforward enough and working well.
Where I am having issues, though, is determining how to properly initialize MassTransit, in the equation. Ideally, I want to have a generic interface to wrap the ConsumeContext instance and allow for me to set up the events. I do not seem to be able to fully set up the instance from within Sample.Infrastructure, as the infrastructure does not/should not know what the events are. I would assume that the consumer classes should exist in Sample.Application, and I do not think that the infrastructure should have a dependency on knowing the consumers.
On startup, System.Web will load the NinjectModule from each System.Application and System.Infrastructure. Does that mean that System.Web should have explicit knowledge of the consumer classes, so that it can configure the IBusControl instance, or is there a more elegant solution?
Right now, the path that I think I am going down is that Sample.Web will load the NinjectModule instances, as it does, and then I will configure the ConsumeContext from Application_Start, after I have explicitly loaded the consumers. However, that would mean that I would have to rebuild/redeploy Sample.Web if I ever add consumers, which is less than ideal and is the root of my concerns. Assuming that consumers are defined within Sample.Application, and all event publications and subscriptions exist within Sample.Application, having to touch either Sample.Web or Sample.Infrastructure to add a consumer is code smell.
Many thanks, in advance.
Edit
As always, after hitting submit, something else comes to mind. I think that one possible solution may be to have Sample.Web as Sample.Application for the known endpoints. Since all events will be published and subscribed from Sample.Application, it would make some sense to have Sample.Web create the actual instance in Sample.Infrastructure and compose the endpoints from what it learns from Sample.Application.
Am definitely open to other solutions, though.

ASP.NET MVC 3 RTM way of ServiceLocator

I'm a little confused with IServiceLocator, IMvcServiceLocator, IDependencyResolver, etc...
What is the ASP.NET MVC 3 RTM way of locating services?
All I need is to access something like
T Resolve<T>();
T Resolve<T>(string key);
from anywhere (including another assembly).
EDIT: example
My web app has a kind of modular architecture. Themes are one aspect of modules. Each theme is an individual class library. It's not possible to know what services a theme needs. E.g. some view might display a tag cloud widget and that widget needs an instance of TagRepository.
Currently I'm using Windsor for IoC and I could expose that container for modules. But I don't really want to make every module depend on Windsor. I would like to know if there's a solution in standard Mvc library since modules need a reference to that anyway.
Asp.net Mvc doesn't have it's own DI container. You would have to implement IDependencyResolver. Take a look at this question: Castle Windsor Dependency Resolver for MVC 3

How do I use dependency injection with an ASP.NET MVC model?

I would like to inject a dependency into an ASP.NET MVC model, but I can't figure out where in the pipeline to do the injection.
It's very straightforward with a ControllerFactory, but not nearly as much when dealing with models.
You can find a reasonable How-To on Shiju Vargheses Blog: ASP.NET MVC Tip: Dependency Injection with Unity Application Block
usually i inject dependencies in the controller like this
PersonController(IPersonRepository r)
{
\\ constrtuctor code
}
in the models probably when need some instance of something that inherits an interface you do something like this :
var r = container.Resolve<IPersonRepository>();
I ended up creating a service locator: http://martinfowler.com/articles/injection.html#UsingAServiceLocator
I find it easier than dealing with an IoC container and trying to insert my DI code all over the MVC pipeline.
I'd recommend reviewing S#arp Architecture
http://www.sharparchitecture.net/
Open source framework addon for asp.net mvc.
Are you completely sure you need to inject a dependency into your domain model itself? An entity or business object will typically encapsulate the state and expose methods to modify that state according to business rules. Code that does not fall into this category typically will be found in a service. Have you read into the concept of a domain service at all? Perhaps using one would better suit your needs and you won't need to inject any dependencies into your domain itself.
Checkout this sample I've created based on Ayende's explanations on his blog. Basically, I use Castle as my IoC container and I use Mvc Contrib to add all controllers to the container and make Mvc get them from it. Then I can inject anything into the containers, such as NHibernate ISession.
If you want to inject stuff inside your model classes (entities), NH now supports Dependency Injection of Hibernate-managed objects. See this, this, and this for specific examples for Spring and Windsor.
What your talking about is more along the lines of the Active Record pattern.
Whether AR is possible or not will depend on which ORM/DAO your using.
The AR pattern is generally better suited for small projects.

Resources