How to register generic UnitOfWork<TContext> with non generic IUnitOfWork in Castle Windsor?

60 Views Asked by At

This is my code:

public interface IUnitOfWork : IDisposable
{
    IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;

    void Save();
}




  public class UnitOfWork<TContext> : IUnitOfWork where TContext : IDbContext, new()
  {
    private readonly IDbContext _ctx;
    private readonly Dictionary<Type, object> _repositories;
    private bool _disposed;
...................

EmployeeService.cs

public class EmployeeService : EntityService<Employee>, IEmployeeService
{
    readonly IUnitOfWork _unitOfWork;
    readonly IRepository<Employee> _repository;
........

in console app when I call:

var employeeService = Injector.Instance.Resolve<IEmployeeService>();

I am getting below error message:

An unhandled exception of type 'Castle.MicroKernel.Handlers.GenericHandlerTypeMismatchException' occurred in Castle.Windsor.dll Additional information: Types EfContext.DAL.IDbContext don't satisfy generic constraints of implementation type EfContext.DAL.UnitOfWork1 of component 'EfContext.DAL.UnitOfWork1'.this is likely a bug in the IGenericImplementationMatchingStrategy used (EfContext.DependencyInjection.UseStringGenericStrategy)

public class ConsoleAppInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {


        container.Register(Component.For(typeof(IUnitOfWork)).ImplementedBy(typeof(UnitOfWork<>), new UseStringGenericStrategy()).LifestyleTransient());

    }
}

    public class UseStringGenericStrategy : IGenericImplementationMatchingStrategy
    {
        public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
        {
            if (context.RequestedType == typeof(IUnitOfWork))
            {
                var res = new[] { typeof(object) };
                return res;
            }
            return null;
        }
    }
1

There are 1 best solutions below

0
hms On

I have fixed my issue with changing the register line to:

// register
container.Register(Component.For(typeof(IUnitOfWork)).ImplementedBy(typeof(UnitOfWork<MyDbContext>),
    new UseTypeGenericStrategy()).LifestyleTransient());