在dotnet中的控制器中包含自定义类时调用工厂

时间:2017-08-16 23:38:00

标签: c# asp.net .net-core

我有一个网络服务(dotnet核心1.1)。

我已经在我的控制器构造函数中创建了一个我希望通过依赖注入显示的类。这可以解决......

Startup.cs有这样的......

public void ConfigureServices(IServiceCollection services)
{
    // ... stuff ...
    services.AddSingleton<IMyClassFactory, MyClassFactory>();
}

MyController.cs有这样的东西:

public MyController(IConfigurationRoot config, ILogger<MyController> logger, IMyClassFactory mcf)
{
    // ... stuff ...

    // Here I can grab "mcf" and grab an instance.  Make a call like this:
    // _myclass = mcf.GetMyClass(this.GetType().Name) 
}

问题是,我希望行为更像ILogger。也就是说,我没有在Startup.cs中将ILogger添加到服务集合中,但不知何故,ILoggerFactory为我的控制器提供了它想要的记录器。

我错过了什么?请原谅,我是dotnet的新手。

1 个答案:

答案 0 :(得分:1)

services.AddSingleton(typeof(IFoo<>), typeof(FooHelper<>));

其中:

public interface IFoo<T> where T : class
{
  string Process(T value);
}

public class FooHelper<T> : IFoo<T> where T : class
{
  public string Process(T value)
  {
    return "DepController";
  }
}

让你使用:

public FooController(IFoo<FooController> helper)

这是一个有点模糊的用例,我很少看到它被使用。请注意,您无法使用services.AddSingleton(typeof(IFoo<>), (ctx) => { ... })指定实施的具体结构,因为在这种情况下无法访问T,您只需获取:

  

System.ArgumentException:打开通用服务类型&#39; LearnWebApi.Core.IFoo`1 [T]&#39;需要注册一个开放的通用实现类型。

如果您想要自定义行为,我相信您的投注选项是将自定义工厂注入控制器并使用以下内容:

IFoo<Thing> _helper;

...

public FooController(FooFactory factory) {
  _helper = factory.Resolve<Thing>();
}