2

I'm trying to follow this tutorial using StructureMap : http://iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Action-Filters.aspx

What I'm trying to figure out is the StructureMap equivalent of this line:

var container = (ICanResolveDependencies) HttpContext.Current.ApplicationInstance;

I want to get the container back, so I can resolve dependencies there manually.

This is how I am setting the dependencyresolver in global.asax

            GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
            new StructureMapDependencyResolver(container));
1
  • 1
    This question has nothing to do with NHibernate. You should remove that tag. Commented Jun 22, 2012 at 21:53

1 Answer 1

3

You could just require IContainer dependency in your action filter's constructor. If it's not registered automatically by StructureMap, you could register it with:

For<IContainer>().Use<Container>();

Edit

Option 1: Couldn't you just use something like:

GlobalConfiguration.Configuration.ServiceResolver.GetService(...)
// or (not sure what would be the right syntax)
GlobalConfiguration.Configuration.ServiceResolver.Current.GetService(...)

There got to be some way of retrieving the current service resolver once you set it.

Option 2: With regular MVC you can get the current resolver like this:

DependencyResolver.Current

And use it like this:

DependencyResolver.Current.GetService()

Looks like WebAPI doesn't use DependencyResolver, but according to this blog post, you could set it like this:

DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
// this override is needed because WebAPI is not using DependencyResolver to build controllers
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
    DependencyResolver.Current.GetService,
    DependencyResolver.Current.GetServices);

Now try to use DependencyResolver.Current from your action filter.

Option 3: Use ObjectFactory.GetInstance directly - Probably not the best idea in MVC project, since it should already be encapsulated in IDependencyResolver instance.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure if it matters, but this is MVC4. Everything I've looked at says that I need to get fancy if I want to inject into my filters/attributes. Can you provide a more detailed example?
Sorry, I thought that you are already using constructor injection in your action filter. I have edited the answer. See if anything of these could help.
You're the man! I went with option1. Option2 gets to be a pain because there are 2 identical interfaces for resolvers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.