Unity Unified Registry Type for Non-Common Interface

my script looks (to me) very straightforward, but I could not find a resolution.

I have this script

public class Class<T> : IInterface where T : class { } 

the interface cannot be made universal (from the WCF library).

so I want to register an interface like this

 container.RegisterType(typeof (IInterface ), typeof (Class<>)); 

and then enable it with T

How can i do this? What am I missing?

my intention is doing something like

 container.Resolve<IInterface>(/* specify T */); 
+4
source share
2 answers

If you do not need to allow the use of an uncontrolled interface, you can create your own managed interface that uses generics and is derived from the uncontrolled interface. You can then register an open pedigree and enable closed generic types.

 public interface IControlled<T> : IUncontrolled {} public class Controlled<T> : IControlled<T> {} container.RegisterType(typeof(IControlled<>), typeof(Controlled<>)); IUncontrolled instance = container.Resolve<IControlled<string>>(); 
+8
source

What am I missing?

You are missing a factory.

Think about it, there are no magical leprechauns working on the background, guessing the type you need. You need to provide it. Or explicitly indicating that T when setting:

 container.RegisterType( typeof(IInterface), typeof(Class<SomeType>)); 

Or by creating a factory where you pass T at runtime:

 public interface IInterfaceFactory { IInterface Create<T>(); } 

factory can be registered as follows:

 container.RegisterInstance<IInterfaceFactory>( new InterfaceFactory(container)); 

And the implementation may look like this:

 public class InterfaceFactory : IInterfaceFactory { private readonly IUnityContainer container; public InterfaceFactory(IUnityContainer container) { this.container = container; } public IInterface Create<T>() { return this.container.Resolve<Class<T>>(); } } 

Now you can enter IInterfaceFactory into consumers who need to work with IInterface , and they can request the version they need by calling the Create<T>() method.

UPDATE

If you think this is too much code, you can also register the factory delegate as follows:

 container.RegisterInstance<Func<Type, IInterface>>( type => container.Resolve( typeof(Class<>).MakeGenericType(type))); 

This is basically the same, but is now included in the delegate. Now your consumers can depend on Func<Type, IInterface> instead of IInterfaceFactory and pass the type instance to the delegate.

I personally prefer to use a descriptive interface like IInterfaceFactory . It depends on you.

+8
source

Source: https://habr.com/ru/post/974893/


All Articles