微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个Web服务(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的新手.

解决方法

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: Open generic service type ‘LearnWebApi.Core.IFoo`1[T]’ requires registering an open generic implementation type.

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

IFoo<Thing> _helper;

...

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐