c# - 使用 Autofac 实现 N 层架构时获取空参数
问题描述
我创建了这个简单的 WebAPI 项目,其中包含以下库类
- 协调(服务层)
- 域(业务层)
- 数据(数据层)
- Dtos(Webapi 的 Dtos)
基本上是 WebAPI 项目调用(参考)Dtos 和协调。协调调用域和域调用数据。
这就是我的结构的样子。
我的问题是使用 Autofac 实现依赖注入。我可以调用协调层,当我尝试调用域层时,这是它感到困惑的地方。
这就是我定义我的注册类型的方式
public class AutofacWebapiConfig
{
public static IContainer Container;
public static void Initialize(HttpConfiguration config)
{
Initialize(config, RegisterServices(new ContainerBuilder()));
}
public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
private static IContainer RegisterServices(ContainerBuilder builder)
{
//Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(Assembly.Load(nameof(Coordination)))
.Where(t => t.Namespace.Contains("Services"))
.As(t => t.GetInterfaces().FirstOrDefault(i => i.Name == "I" + t.Name));
builder.RegisterAssemblyTypes(Assembly.Load(nameof(Domain)))
.Where(j => j.Namespace.Contains("Domain"))
.As(j => j.GetInterfaces().FirstOrDefault(i => i.Name == "I" + j.Name));
//Set the dependency resolver to be Autofac.
Container = builder.Build();
return Container;
}
}
- 会出现一些问题。首先它不知道如何找到域,因为理论上 WebAPI 不与域层对话。
- 我确实将它添加为参考,但现在我得到一个空参数错误。服务类型不能为空。
服务实现中没有什么能让我跳出来的
public class StudentService : IStudentService
{
private readonly IStudentDomain studentDomain;
public StudentService(IStudentDomain _studentDomain)
{
this.studentDomain = _studentDomain;
}
public async Task<StudentDto> GetStudentByID(string id)
{
var test = this.studentDomain.getStudentByID(id);
}
}
这是我的域实现
public class StudentDomain : IStudentDomain
{
public StudentDomain()
{
}
/// <summary>
/// Return student
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
StudentEntity IStudentDomain.getStudentByID(string id)
{
StudentEntity student = new StudentEntity("dd", "aa", "ddd");
return student;
}
}
对不起,我的操作系统是法语,但这只是意味着该值为空。全栈错误
System.ArgumentNullException
HResult=0x80004003
Message=La valeur ne peut pas être null.
Nom du paramètre : serviceType
Source=Autofac
StackTrace:
at Autofac.Core.TypedService..ctor(Type serviceType)
at Autofac.RegistrationExtensions.<>c__DisplayClass14_0`3.<As>b__0(Type t)
at Autofac.RegistrationExtensions.<>c__DisplayClass13_0`3.<As>b__0(Type t)
at Autofac.Features.Scanning.ScanningRegistrationExtensions.<>c__DisplayClass8_0`3.<As>b__0(Type t, IRegistrationBuilder`3 rb)
at Autofac.Features.Scanning.ScanningRegistrationExtensions.ScanTypes(IEnumerable`1 types, IComponentRegistryBuilder cr, IRegistrationBuilder`3 rb)
at Autofac.Features.Scanning.ScanningRegistrationExtensions.ScanAssemblies(IEnumerable`1 assemblies, IComponentRegistryBuilder cr, IRegistrationBuilder`3 rb)
at Autofac.Features.Scanning.ScanningRegistrationExtensions.<>c__DisplayClass0_0.<RegisterAssemblyTypes>b__0(IComponentRegistryBuilder cr)
at Autofac.ContainerBuilder.Build(IComponentRegistryBuilder componentRegistry, Boolean excludeDefaultModules)
at Autofac.ContainerBuilder.Build(ContainerBuildOptions options)
at CB.WebAPI.App_Start.AutofacWebapiConfig.RegisterServices(ContainerBuilder builder) in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\AutofacWebapiConfig.cs:line 43
at CB.WebAPI.App_Start.AutofacWebapiConfig.Initialize(HttpConfiguration config) in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\AutofacWebapiConfig.cs:line 21
at CB.WebAPI.App_Start.Bootstrapper.Run() in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\Bootstrapper.cs:line 14
at CB.WebAPI.WebApiApplication.Application_Start() in C:\source\repos\CB.WebAPI\CB.WebAPI\Global.asax.cs:line 18
在这里,我添加了 global.asax.cs 文件。第 18 行是我的 bootstrapper.run();
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
Bootstrapper.Run();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
解决方案
注册好像有问题,Domain
因为StudentEntity
没有对应的接口,.As(j => j.GetInterfaces().FirstOrDefault(i => i.Name == "I" + j.Name))
找不到对应的接口。
如果您不想手动添加带有接口的所有类型,请尝试以下操作:
builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
.Where(j => j.Namespace.Contains("Domain"))
.AsImplementedInterfaces()
您可能想要/需要区分具有接口和没有接口的类型,您可以尝试下一种方法:
builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
.Where(j => j.Namespace.Contains("Domain") && j.GetInterfaces().Any())
.AsImplementedInterfaces()
builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
.Where(j => j.Namespace.Contains("Domain") && !j.GetInterfaces().Any())
.AsSelf();
附言
另外我建议将 all 更改Assembly.Load(nameof(SOME_NAME))
为typeof(TYPE_NAME).Assembly
,我认为它更具可读性和明显性。
推荐阅读
- c# - 如何使用没有数据库的 C# 构建从 DataGridView 中删除行的方法
- javascript - 如何在多行字符串中找到字符位置(行,列)?
- jquery - 图像轮播在不同的浏览器上无法正确显示
- google-cloud-datalab - 我无法在 Google Cloud Datalab 上使用“云翻译 API”
- visual-studio - 在 Visual Studio 的拆分窗口中打开已在另一个窗口中打开的文件
- reactjs - 外部化 react 和 react-dom 依赖项是否会增加反应应用程序的加载时间
- spring-boot - spring boot 如何分别为管理员和用户配置安全性
- c# - 从 C# 中的文件开头写入二进制文件块
- zapier - Zapier API 配置:发送表单数据而不是 json 请求正文
- angular - 找不到“AppServerModule”的 NgModule 元数据