0

I would like to be able to inject a DefaultService object that implements IService<in T>.

For example if I've got a constructor:

public FunClient(IDefaultService<FunModel> service) { ... }

But I don't have a FunService : IService<FunModel> developed, I would like to be able to tell Autofac to not throw an exception, but instead resolve/inject a DefaultService instance.

edhedges
  • 2,722
  • 2
  • 28
  • 61
  • How *autofac* should find the default implementation of the interface. You can do a *RegistrationSource* to provide it but which *Type* should Autofac choose ? – Cyril Durand Apr 28 '15 at 19:01
  • What is the relationship between `DefaultService` and `IDefaultService` and between `IService` and `IDefaultService`? – Steven Apr 28 '15 at 19:53
  • @CyrilDurand What do you mean by "you can do a RegistrationSource to provide"? The type could be any type that isn't registered in autofac. – edhedges Apr 28 '15 at 20:28

1 Answers1

2

What you are looking for is the registration of open generic types. You will have to create a Null Object implementation for IDefaultService<T> and register that using RegisterGeneric, as follows:

public class NullDefaultService<T> : IDefaultService<T> {
   // Implement methods here
}

// registration
builder.RegisterGeneric(typeof(NullDefaultService<>))
    .As(typeof(IDefaultService<>));
Steven
  • 166,672
  • 24
  • 332
  • 435
  • I have tried this, but how would `IDefaultService<>` look as a constructor parameter? – edhedges Apr 28 '15 at 20:24
  • @edhedges: I'm not sure what you mean. Can you elaborate? – Steven Apr 28 '15 at 20:25
  • In my question I have `public FunClient(IDefaultService service) { ... }`. The goal is to configure autofac or write some sort of extension if need be to have `NullDefaultService` be resolved when the container can't find anything registered for `IDefaultService`. – edhedges Apr 28 '15 at 20:27
  • @edhedges: Did you try my suggestion? That is exactly what `RegisterGeneric` does. It functions as fallback mechanism in case there is no other registration. – Steven Apr 28 '15 at 20:28
  • 1
    I did try it, but it could have been that I didn't set it up correctly with some of my existing registrations. I'll give it another shot, thanks. – edhedges Apr 28 '15 at 20:29
  • Looks like it worked, thanks! I actually had that registration, but my implementation of `DefaultService` was incorrect and I was getting an exception when the builder was building the container. – edhedges Apr 28 '15 at 20:54