上下文是ASP.NET Core。
请考虑以下最小设置。
public class ExampleController : ControllerBase
{
public ExampleController(IExempleService exampleService)
{
(...)
public interface IExampleService
{
ExampleStruct Foo();
}
public readonly struct ExampleStruct (...)
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IInverterService, InverterService>();
这里有一个宣传链。
public
。 我感到恶心。 这有实际后果:
我想这里有两个问题:
单元测试和internal
与InternalsVisibleToAttribute 一起使用。
答案 0 :(得分:2)
所有功劳应归功于@MichaelRandall:
您可以将控制器设置为内部控制器,只需使用ControllerFeatureProvider使它们可被发现,请查看此stackoverflow.com/a/50906593/1612975 – Michael Randall
public void ConfigureServices(IServiceCollection services)
{
(...)
services
.AddControllers(options => ...)
.ConfigureApplicationPartManager(manager =>
{
manager.FeatureProviders.Add(new MyControllerFeatureProvider());
})
(...)
internal class MyControllerFeatureProvider : ControllerFeatureProvider
{
protected override bool IsController(TypeInfo typeInfo)
{
// https://source.dot.net/#Microsoft.AspNetCore.Mvc.Core/Controllers/ControllerFeatureProvider.cs,41
// contains
//
// // We only consider public top-level classes as controllers. IsPublic returns false for nested
// // classes, regardless of visibility modifiers
// if (!typeInfo.IsPublic)
// {
// return false;
// }
if (typeInfo.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) &&
typeInfo.IsDefined(typeof(ApiControllerAttribute)))
{
System.Diagnostics.Debug.WriteLine($"Found controller '{typeInfo.Name}'");
return true;
}
if (typeInfo.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
System.Diagnostics.Debug.Fail($"Found class that ends in 'Controller' but will not be registered as a controller: {typeInfo.Name}");
}
return false;
}
}
答案 1 :(得分:1)
您 可以 使您的控制器 internal
,只需将其设置为可发现与ControllerFeatureProvider
从
ApplicationPart
实例列表中发现控制器。
Asp.Net Core中有4种方式定义控制器:
最后一点(定义自定义控制器类型)对您来说internal
控制器的情况最为重要。
为此,您将需要
ControllerFeatureProvider
IsController
并为发现类型实施任何逻辑例如
internal class MyControllerFeatureProvider : ControllerFeatureProvider
{
protected override bool IsController(TypeInfo typeInfo)
{
...
ConfigureApplicationPartManager
将其添加到FeatureProviders
例如
.ConfigureApplicationPartManager(manager =>
{
manager.FeatureProviders.Add(YourControllerFeatureProvider)
...