Injecting a dependency into a static class
Asked Answered
M

1

13

What configuration do I need to setup a static property dependency using Windsor container?

I have the following class at the moment and I would like the Logger property to be injected.

static class StuffDooer 
{
   static ILogger Logger { get; set; }

   static StuffDooer() { Logger = NullLogger.Instance; }
}

Here's my configuration although, this facility seems to automatically find instance properties not problem, the static version is not being set.

<facility id="logging"
          type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging"
          loggingApi="nlog"
          customLoggerFactory="Castle.Services.Logging.NLogIntegration.NLogFactory"
          configFile="Configuration/nlog.config" />
Mccabe answered 12/7, 2010 at 12:11 Comment(0)
I
28
StuffDooer.Logger = container.Resolve<ILoggerFactory>().GetLogger(typeof(StuffDoer));

If you think it's ugly, that is the correct reaction. Statics and and IoC don't mix, same as alcohol and driving.

Internationalist answered 12/7, 2010 at 12:59 Comment(2)
LOL Ok, I might rethink my class design insteadMccabe
The only difference is that in most places there is a maximum allowed blood alcohol level whilst driving (here it is 0.05%). IOC and statics have a no tolerance approach.Cheek

© 2022 - 2024 — McMap. All rights reserved.