Try our conversational search powered by Generative AI!

structuremap usage


Hi there,

I am looking to use an IOC and structuremap comes with episerver by default.

Is there a clear example showing how to use it, from registering your types to actually getting stuff out? I am using structure map 3.1 with epi server 9. 

I found some examples on using ObjectFactory, but that's going away.

I can see a DependencyResolverInitialization in Business/Initialization. I can register my types there, but I have no idea how to get them out where I need them.

Nov 05, 2015 14:15

I found a way of doing it, just wondering if it is the right way.

Basically I register my type in DependencyResolverInitialization :


Then I use it in a WebApi2 controller in Business/ApiControllers like this:

var myObject = System.Web.Mvc.DependencyResolver.Current.GetService(typeof(MyInterface));

var data= ((MyInterface)myObject).MyMethodFromInterface();

It does work and gets my data back succesfully. Does that look right?   

Edited, Nov 05, 2015 14:25

You should be able to use ServiceLocator.Current.GetInstance<YourInterface>() if I'm not misstaking.

Nov 05, 2015 14:57

that does not work for me.

Nov 05, 2015 15:29

actually, it does work as long as you use the ServiceLocator from EPiServer.ServiceLocation. StructureMap also has a ServiceLocator

so this works :


Thank you

Nov 05, 2015 15:39

If you are setting up the MVC DependencyResolver to use the StructureMap container exposed by EPiServer, you are basically querying the same container, so using the EPiServer ServiceLocator or the DependencyResolver should not matter.

Edited, Nov 05, 2015 21:12

I would avoid to use these 2 types directly *unless* there is no other way around it (attributes may come in mind). As direct usage of these types in your code violates dependency injection practices (injection here is the keyword). Other than requesting necessary interface implementation directly from the component code, I would rather recommend to ask somebody from "above" to inject them into the component. And this "above" guy is responsible for collecting necessary dependencies. If you scroll picture up till the top - most probably everything will begin in something like Mvc controller factory that will use DependencyResolver to resolve dependencies and in turn - that will query StructureMap container built by EPiServer (and probably your own custom code as well). This is the place where composition container gets built.

Edited, Nov 06, 2015 10:44
Nov 06, 2015 10:58

thank you all

Nov 06, 2015 11:31
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.