简体   繁体   English

解决Asp.Net Core中的依赖性

[英]Resolving Dependency in Asp.Net Core

I am working on a generic repository pattern on EF Core and I have a problem resolving the dependency of my Repository on Asp.Net Core. 我正在使用EF Core上的通用存储库模式,但是在解决我的存储库对Asp.Net Core的依赖性时遇到问题。 Using Unity i am Able to Solve the dependency here are my code: 使用Unity我能够解决依赖关系,这是我的代码:

Using Unity 使用Unity

 //here is the Line I Cant Resolve
.RegisterType<IRepositoryAsync<Movie>, Repository<Movie>>()

.RegisterType<IMovieService, MovieService>()

Asp.Net Core Asp.Net核心

services.AddScoped<IRepositoryAsync<Movie>, Repository<Movie>>();

services.AddTransient<IMovieService, MovieService>();

and I am getting Error 我得到错误

InvalidOperationException: Unable to resolve service for type 'Repository.Pattern.DataContext.IDataContextAsync' while attempting to activate 'Repository.Pattern.Core.Repository`1[Sample.Models.Movie]'.

Can anyone has a clear documentation on how Native Dependency Injection works on Asp.Net Core 任何人都可以清楚了解本机依赖注入如何在Asp.Net Core上工作

Microsoft.Extensions.DependencyInjection uses constructor injection to inject dependencies into resolved services. Microsoft.Extensions.DependencyInjection使用构造函数注入将依赖项注入已解析的服务。 Your service locator needs to know how to construct these dependencies to produce the requested service. 您的服务定位器需要知道如何构造这些依赖关系以产生所请求的服务。

Very basically if you want to resolve IMyService with a default constructor of IMyService(IMyOtherService otherService) you need to register IMyOtherService as well. 基本上,如果要使用IMyService(IMyOtherService otherService)的默认构造函数解析IMyService ,则还需要注册IMyOtherService

In your example you need to register Repository.Pattern.DataContext.IDataContextAsync in order to resolve IRepositoryAsync<Movie> . 在您的示例中,您需要注册Repository.Pattern.DataContext.IDataContextAsync以便解析IRepositoryAsync<Movie>

Comprehensive documentation is here https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection 完整的文档在这里https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM