I have a couple classes in a project I'm working on that only register event handlers.
public class EventLogger
{
public EventLogger(EventRaiser someObject)
{
someObject.EventRaised += logThatEvent;
}
}
The EventLogger
is either running or not based on some run time status checks at program startup, so I initialize it in a factory class:
public class EventLoggerFactory
{
public EventLogger GenerateEventLogger(StatusChecker status, EventRaiser objectToListenTo)
{
if (status.EventLoggerNeeded)
{
return new EventLogger(objectToListenTo);
}
return null; // Spring.NET doesn't let you return null
}
and in Spring.NET config:
<object id="EventLogger" type="MyProject.EventLogger" factory-object="EventLoggerFactory" factory-method="GenerateEventLogger">
<constructor-arg name="status" ref="StatusChecker"/>
<constructor-arg name="objectToListenTo" ref="EventRaiser"/>
</object>
Since I can't return null
for my factory method, I've tried the following:
public class EventLogger
{
// Actual implementation elided
private EventLogger(){}
internal static EventLogger DummyInstance
{
get { return new EventLogger(); }
}
}
public class EventLoggerFactory
{
public EventLogger GenerateEventLogger(StatusChecker status, EventRaiser objectToListenTo)
{
if (status.EventLoggerNeeded)
{
return new EventLogger(objectToListenTo);
}
return EventLogger.DummyInstance;
}
Is this a valid use of the Dummy Object pattern? It feels weird to me to have to adjust the internals of my class to fit the Dependency Injection container I'm using, but I'm unable to find another way.
(Also I'm tagging this spring
because I can't create a spring.net
tag)