2017-08-16 67 views
3

我有一个Web服务(dotnet核心1.1)。当在dotnet中包含控制器中的自定义类时调用工厂

我创建了一个类,我想通过依赖注入显示在我的控制器的构造函数中。这样可以...

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的行为。也就是说,我没有将一个ILogger添加到Startup.cs中的服务集合中,但不知何故,ILoggerFactory为我的控制器提供了它想要的记录器。

我缺少什么?请原谅,我是新来的dotnet。

回答

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) => { ... })指定执行的到底如何构造,因为没有办法访问吨这种情况下,你会只得到:

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

如果你想定制行为,我相信你的赌注的选择是一个自定义的工厂注入到控制器,并使用类似:

IFoo<Thing> _helper; 

... 

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