structuremap usage

Vote:
 

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.

#140977
Nov 05, 2015 14:16
Vote:
 

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

Basically I register my type in DependencyResolverInitialization :

container.For<MyInterface>().Use<MyImplementationClass>();

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?   


                        
#140981
Edited, Nov 05, 2015 14:25
Vote:
 

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

#140982
Nov 05, 2015 14:57
Vote:
 

that does not work for me.

#140987
Nov 05, 2015 15:29
Vote:
 

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

so this works :

EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<MyInterface>();


Thank you

#140989
Nov 05, 2015 15:39
Vote:
 

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.

#140993
Edited, Nov 05, 2015 21:12
Vote:
 

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.

#141004
Edited, Nov 06, 2015 10:44
Vote:
 
#141007
Nov 06, 2015 10:58
Vote:
 

thank you all

#141011
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.