Search code examples
c#asp.netdependency-injectiondelegatescastle-windsor

how to inject Func<T,U> with Windsor container


 public BranchUOW(Func<FoodieTenantContext,BranchRepository> branchRepository, 
        Func<FoodieTenantContext, BranchContactRepository> branchContactRepository,
        FoodieTenantContext ctx, IMapperService mapperService)
        : base(ctx)
    {
        _ctx = ctx;
        _branchRepository = branchRepository(ctx);
        _branchContactRepository = branchContactRepository(ctx);
        _mapperService = mapperService;
    }

Where BranchRepository looks as

 public BranchRepository(FoodieTenantContext ctx)
        : base(ctx)
    {
    }

Tried with the below permutations

  container.Register(
          Component.For<Func<FoodieTenantContext, BranchRepository>>()
          .ImplementedBy(typeof(IRepository<BranchRepository>))
          .LifestyleTransient()
         );

        container.Register(
           Component.For<Func<FoodieTenantContext, BranchContactRepository>>()
           .ImplementedBy(typeof(IRepository<BranchContactRepository>))
           .LifestyleTransient()
          );

But unable to instansitae & throws the below error.

Type foodie.common.Repository.IRepository1[[foodie.tenant.EF.Repository.Domain.BranchRepository, foodie.tenant.EF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] is abstract.\r\n As such, it is not possible to instansiate it as implementation of service 'foodie.common.Repository.IRepository1[[foodie.tenant.EF.Repository.Domain.BranchRepository, foodie.tenant.EF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Did you forget to proxy it?

Thanks.


Solution

  • You can try this:

    container.Register(
        Component.For<BranchRepository>(),
        Component.For<Func<FoodieTenantContext, BranchRepository>>()
        .Instance(c => container.Resolve<BranchRepository>(new { ctx = c }))
        .LifestyleTransient()
    );
    

    But I would recommend rather to go for typed factory.

    https://github.com/castleproject/Windsor/blob/master/docs/typed-factory-facility-interface-based.md