RandomUs1r RandomUs1r -4 years ago 67
C# Question

How can I register an interface that inherits from an interface in Unity

Say I have an interface that inherits another interface:

public interface IInvoiceFactory : IConfigFactory<Invoice, InvoiceRequest>

This doesn't resolve:

container.RegisterType<IConfigFactory<Invoice, InvoiceRequest>, IInvoiceFactory>();
container.RegisterType<IInvoiceFactory, InvoiceFactory>();

Is it possible to have an interface inherit another interface in the DI world?

Answer Source

You could do this, which isn't quite what you wanted, but may resolve what you need:

container.RegisterType<IInvoiceFactory, InvoiceFactory>();
container.RegisterType<IConfigFactory<Invoice, InvoiceRequest>, InvoiceFactory>();

That will mean both of these will resolve an instance of InvoiceFactory:

var factory = container.Resolve<IInvoiceFactory>();
var factory = container.Resolve<IConfigFactory<Invoice, InvoiceRequest>>();

Other containers give you ways of registering all interfaces implemented by a type, and I'm guessing Unity provides that mechanism, too, so there is likely a better way of doing this. As I said though, it depends if this solves your situation or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download