如何使用Web API Controller中的参数将依赖项注入工厂

时间:2017-07-21 16:44:30

标签: c# asp.net-web-api dependency-injection inversion-of-control ninject

我有一个安装了以下软件包的Web API项目:

  • Ninject
  • Ninject.Extensions.Factory
  • Ninject.MVC5
  • Ninject.Web.Common(和WebHost)
  • Ninject.Web.WebApi(和WebHost)

我试图用Http方法注入参数。其中一个依赖项本身依赖来处理另一个也需要Http方法参数的依赖项。我该如何构建这个?我得到了"确保你的控制器没有参数#34;访问端点时出错。

public interface IFooFactory {
    Foo.Foo Create(string arg1, IBar barService);
}

public class FooFactory : IFooFactory {
    private readonly IResolutionRoot resolutionRoot;

    public FooFactory(IResolutionRoot resolutionRoot) {
        this.resolutionRoot = resolutionRoot;
    }

    // Need dependency injected here... How? barService also needs http args
    public Foo.Foo Create(string arg1, IBarService barService) {
        return resolutionRoot.Get<Foo.Foo>(
            new ConstructorArgument("arg1", arg1),
            new CosntructorArgument("barService", barService)
            );
    }
}

在这种情况下,IBarService barService需要注入FooFactory,而IBarService需要使用Http参数进行实例化。我只是不知道如何构建这个。我需要再建一家工厂吗?

这是我的 NinjectWebCommon.cs

private static void RegisterServices(IKernel kernel) {
    kernel.Bind<IFooFactory>()
        .To<FooFactory>()
        .InRequestScope();

    // add a bar factory?
    kernel.Bind<IBarFactory>()
        .To<BarFactory>()
        .InRequestScope();
}

如果我添加IBarFactory barFactory,我该如何将其传递给FooFactory

我为IBarService创建了另一个工厂,从Http传递了参数:

第二工厂

public interface IBarFactory
{
    BarService.BarService Create(string arg1);
}

public class BarFactory : IBarFactory
{
    private readonly IResolutionRoot resolutionRoot;

    public BarFactory(IResolutionRoot resolutionRoot)
    {
        this.resolutionRoot = resolutionRoot;
    }

    public BarService Create(string arg1)
    {
        return resolutionRoot.Get<BarService>(
            new ConstructorArgument("arg1", arg1));
    }
}

如何使用HTTP args

public FooFooController : ApiController {

    private readonly IFooFactory fooFactory;
    private readonly IBarFactory barFactory;

    public FooFooController(IFooFactory fooFactory, IBarFactory barFactory) {
        this.fooFactory = fooFactory;
        this.barFactory = barFactory;
    }

    [HttpPost]
    public async Task<JsonResult> Post(string arg1) {
        // arguments are consumed here
        var barService = this.barFactory.Create(arg1);
        var fooService = this.fooFactory.Create(arg1, barService);
    }
}

0 个答案:

没有答案