1
votes

I have the following code :

 public interface IGenericDao<TEntity> where TEntity : IEntity {    }

 public interface IEntity { }

 public abstract class AbstractEntity : IEntity {}

 public interface IMasterEntity : IEntity {}

 public interface IDynamicEntity : IEntity {}

 public class Client : AbstractEntity , IMasterEntity {} 

 public class MasterEntityHandler<TEntity> : IGenericDao<TEntity>, IDisposable where TEntity : IMasterEntity {}

 public class DynamicEntityHandler<TEntity> : IGenericDao<TEntity>, IDisposable where TEntity : IDynamicEntity {}

In the unity container, I made the registration as :

container.RegisterType<IGenericDao<IMasterEntity>, MasterEntityHandler<IMasterEntity>>(new ContainerControlledLifetimeManager());
container.RegisterType<IGenericDao<IDynamicEntity>, MasterEntityHandler<IDynamicEntity>>(new ContainerControlledLifetimeManager());

When trying to resolve with Client class with

container.Resolve<IGenericDao<Client>>();

I am getting an error that

---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Unity.ResolutionFailedException: The current type, Interface.IGenericDao`1[Client], is an interface and cannot be constructed. Are you missing a type mapping?

Tried this registration also, but still same error :

container.RegisterType(typeof(IGenericDao<IMasterEntity>),typeof(MasterEntityHandler<>)
                , new ContainerControlledLifetimeManager());
container.RegisterType(typeof(IGenericDao<IDynamicEntity>),typeof(DynamicEntityHandler<>)
                    , new ContainerControlledLifetimeManager());

and also :

container.RegisterType(typeof(IGenericDao<>),typeof(MasterEntityHandler<IMasterEntity>)
                , new ContainerControlledLifetimeManager());
container.RegisterType(typeof(IGenericDao<>),typeof(DynamicEntityHandler<IDynamicEntity>)
                    , new ContainerControlledLifetimeManager());
1

1 Answers

0
votes

Consider narrowing the scope of the interfaces

public interface IMasterDao<TEntity> : IGenericDao<TEntity>, IDisposable where TEntity : IMasterEntity { }

public interface IDynamicDao<TEntity>: IGenericDao<TEntity>, IDisposable where TEntity : IDynamicEntity {}

public class MasterEntityHandler<TEntity> : IMasterDao<TEntity>, IDisposable where TEntity : IMasterEntity {}

public class DynamicEntityHandler<TEntity> : IDynamicDao<TEntity>, IDisposable where TEntity : IDynamicEntity {}

Remove the interface from the registration and leave it as an open generic registration.

container.RegisterType(typeof(IMasterDao<>), typeof(MasterEntityHandler<>), new ContainerControlledLifetimeManager());
container.RegisterType(typeof(IDynamicDao<>), typeof(DynamicEntityHandler<>), new ContainerControlledLifetimeManager());

The type constraint on the implementation will handle what classes can be used.