4
votes

I'm trying to implement IoC in my app. I have this model:

interface IService;
interface IComponent;

class Service : IService
    Service()

class Component : IComponent
    Component(IService service, object runtimeValue) { }

At some point in my app I need to get a IComponent. My app uses a IoC container (Unity). I can register Service with the container but I can't do the same for Component b/c of its dependency runtimeValue. According to this I have to use a factory and inject that wherever I need to get a IComponent:

interface IComponentFactory
     IComponent CreateComponent(object runtimeValue)

class ComponentProvider : IComponentProvider
     ComponentProvider(IComponentFactory factory) { }

     IComponent CreateAndCacheComponent(object runtimeValue) {
         _component = factory.CreateComponent(runtimeValue)
         return _component
     }

     // other methods

I must be able to register the factory with the container, so it must have only static dependencies. At the same time it must be able to provide a service instance of type IService required to create a component.
Here is the factory implementation. The only thing I could think of was to use a Func<> delegate as dependency:

class ComponentFactory : IComponentFactory
    ComponentFactory(Func<IService> serviceFactoryDelegate)

    IComponent CreateComponent(object runtimeValue) {
        return new Component(serviceFactoryDelegate.Invoke(), runtimeValue)
    }

... and register the delegate with the container as static factory, so that it calls back the container to resolve the service (I'm using Unity 1.2 on .net 2.0):

Container
    .Configure<IStaticFactoryConfiguration>()
    .RegisterFactory<Func<IService>>(container => (Func<IService>)container.Resolve<IService>)

Now I can use the container to resolve a ComponentProvider and get a component based on a runtime value:

// this happens inside CompositionRoot
provider = Container.Resovle<IComponentProvider>()
component = provider.CreateAndCacheComponent("the component")

Now I have some questions about this:

  1. I'm not happy that the factory calls new Component(...). Isn't this poor man's DI?

  2. Does the Hollywood principle still stand when using Func<IService> on factory's constructor? I mean, it ultimately calls container.Resolve<>... kind of like SL. The only difference is the code is in the container registration part of the app rather than inside the factory class.

  3. Is there anything (else) wrong with this implementation, as far as DI and IoC are concerned?

3
Why the need for the delegate? Why can't you inject IService directly?Daniel Hilgarth
Why do you need the Func<IService>? Isn't the whole point to allow your container to resolve this?Jay
@Daniel, @Jay: Injecting the service assumes the same instance will be used to create the component. If the factory had another method which had to create a different object having a IService dependency, then the same service instance would have been used in both methods. Using the delegate allows the container to resolve the service each time it is needed, using its configured lifetime.Suiden
You normally shouldn't care about the lifetime of your services or whether you get the same instance as another consumer. Do you really need different instances of the service?Daniel Hilgarth
Finally I've come across someone else using Funcs like this: nblumhardt.com/2010/01/the-relationship-zoo: if A needs to create an instance of B, then it needs a Func<B> (which I assume would call back the container)Suiden

3 Answers

1
votes
  1. It's a big step away from Poor Man's DI, but it would be nice if you didn't have to change this factory method every time a new dependency gets added to the Component's constructor.
  2. This isn't a problem per se. Think of it like you're injecting an anonymous factory class. It can still be mocked for unit testing, and the bindings can be changed, so you're still getting the benefits of DI. But it is an added layer of abstraction which is probably not necessary. You can still avoid it in this case by injecting the IService directly into the factory, rather than a Func.
  3. Typically when using dependency injection, you want to inject services rather than values. The fact that you're finding that you have to have both may indicate that you need to reconsider your class's API. For example, maybe you should be passing the value in to the methods on the class rather than the constructor. It's hard to say what the best approach would be without knowing more details.
1
votes
  1. No, it isn't. The whole purpose of a factory is to create an instance of a concrete class.
  2. Basically, yes, but as I already asked in my comment, I don't see why this is necessary. You could inject an instance of IService directly
  3. It's a bit more complicated than it needs to be. Why the double redirection IComponentProvider -> IComponentFactory? It looks like IComponentFactory doesn't add any benefit.

    Implement ComponentProvider like this:

    class ComponentProvider : IComponentProvider
    {
        ComponentProvider(IService service) { _service = service; }
    
        IComponent CreateAndCacheComponent(object runtimeValue) {
            _component = new Component(_service, runtimeValue);
            return _component;
    }
    

    This would give you the following benefits:

    1. You get rid of the unnecessary interface IComponentFactory along with the corresponding implementation.
    2. No need to register a factory for IService

Generally speaking, how you implement this it depends on what you really need:

"runtimeValue" can be the same throughout the runtime, e.g. a connection string that is read from the settings. In that case, there would be no need for a factory / provider, you could simply new up the instance and register it with the container. Everyone who needs an IComponent requests one in the constructor instead of the provider.

You would only implement a factory and pass that as a dependency around if the "runtimeValue" really changes between calls to CreateAndCacheComponent.

0
votes

To question 1: there is nothing wrong with calling new in the factory. You have isolated instantiation to one place in your application; you just made that one place the factory instead of the container.

If you ever needed to mock or change implementations, you would just mock or change the factory implementation, rather than the Component alone.