Unity in static methods

maybe a simple problem, but strange why I have no idea how to do this:

Unity (PRISM) and static methods. In this special case, an extension method is used. But in general, how do I access the "single supplied instance" in a static method. Think for example. logging service I want to access the log of some of the things I do inside a static method. Should I actually pass the ref to the logging service when using it?

Example (close to the actual problem)

public static void HookupPrismEvent(ref UIElement, ILogger log) {...}

      

It seems strange, I think I am missing something like Container.Resolve (static resolution). Didn't find anything, but container, unity or static are not the best search terms in the world. Maybe I'll just try, but still, it feels "weird".

So, any comments on HOW and IF to use DI in static methods?

Chris

EDIT - ok, current approach after answer: EDIT2, after thinking about it, removed the container, providing "what is needed" ....

  public static void AttachPrismEvents(this UIElement element, IEventAggregator eA)
    {
        var ev = eA.GetEvent<KeyPressedEvent>();
        element.KeyDown += ((sender, e) => ev.Publish(e));
    }

      

or, upon registration:

  public static void AttachPrismEvents(this UIElement element, ILogger log, IEventAggregator eA)
    {
        log.Debug("Doing stuff");
        var ev = eA.GetEvent<KeyPressedEvent>();
        element.KeyDown += ((sender, e) => ev.Publish(e));
    }

      

+2


source to share


1 answer


Static types and members are usually the enemy of all DI stuff.

You can technically have a static Resolve method, but it won't be a DI, but rather a pattern known as a Service Locator. However, many people (myself included) consider the Service Locator an anti-pattern for several reasons:



  • It makes implicit assumptions about the API usage requirements (the caller is not aware that the service locator needs to be configured correctly before it can be called)
  • Unable to nest containers
  • It introduces a redundant dependency on the service locator itself

If you must have a static method, you must pass the dependency through the Injection method, but I think it is often more useful to revisit the overall design of the API. Often the desired functionality can be modeled as a member on one of the props.

+1


source







All Articles