如何使用Windsor容器注入Func <t,u>

时间:2018-07-22 14:53:05

标签: c# asp.net dependency-injection delegates castle-windsor

 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;
    }

BranchRepository的外观为

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

尝试以下排列

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

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

但无法实例化并抛出以下错误。

  

类型foodie.common.Repository.IRepository 1[[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.IRepository 1 [[foodie.tenant.EF.Repository.Domain.BranchRepository,foodie.tenant.EF,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null ]]'。您忘了代理吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

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

但是我还是建议去打字工厂。

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