Reputation: 2205
I have a WebApi Solution and I am using StructureMap.WebApi2 Nuget Package for Dependency Injection.
I want to use Fody Tracer to weave in trace methods. I am implementing my own custom log adapter which requires me to return an instance of my logger from a static class/method.
What is the proper way for me to use Structure Map to get an instance of my logger from a static class/method?
Upvotes: 1
Views: 1701
Reputation: 9281
Traditionally you would use StructureMap's ObjectFactory.GetInstance<T>
to resolve your static method's dependencies. However, this has since been deprecated as it's typically frowned on because using it tightly couples your code to the IoC container (see this post on the Service Locator anti-pattern).
The next best approach is to create your own static equivalent of the ObjectFactory that returns an IContainer instance, similar to this:
public static class ObjectFactory
{
private static readonly Lazy<Container> _containerBuilder = new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
private static Container defaultContainer()
{
return new Container(x => {
x.AddRegistry(new YourRegistry()) };
});
}
}
See this post for a more in-depth implementation.
Upvotes: 5