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.
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?
You should be able to use ServiceLocator.Current.GetInstance<YourInterface>() if I'm not misstaking.
that does not work for me.
actually, it does work as long as you use the ServiceLocator from EPiServer.ServiceLocation. StructureMap also has a ServiceLocator
so this works :
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.
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.
Here you can find an example on how to use it
thank you all