我正在尝试为实体框架核心实现我的缓存变体。 我所做的就是继承
公共类CustomQueryCompiler:QueryCompiler
然后我尝试将分布式缓存注入到CustomQueryCompiler的构造函数中,但无法解决它。得到此错误:
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'WebApplication6.CustomQueryCompiler'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, CallSiteChain callSiteChain)
我不明白为什么以及如何解决它。
我的创业公司是这样的:
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
options.Configuration = "127.0.0.1:6379,password=P@55w0rd,allowAdmin=true,ssl=False,abortConnect=false");
services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("Default"));
options.ReplaceService<IQueryCompiler, CustomQueryCompiler>();
}
);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
CustomQueryCompiler的构造函数
public class CustomQueryCompiler : QueryCompiler
{
private readonly IQueryModelGenerator _queryModelGenerator;
private readonly IDistributedCache _distributedCache;
public CustomQueryCompiler(IQueryContextFactory queryContextFactory,
ICompiledQueryCache compiledQueryCache,
ICompiledQueryCacheKeyGenerator compiledQueryCacheKeyGenerator,
IDatabase database,
IDiagnosticsLogger<DbLoggerCategory.Query> logger,
ICurrentDbContext currentContext,
IQueryModelGenerator queryModelGenerator, IDistributedCache distributedCache) :
base(queryContextFactory, compiledQueryCache, compiledQueryCacheKeyGenerator, database, logger, currentContext, queryModelGenerator)
{
_queryModelGenerator = queryModelGenerator;
_distributedCache = distributedCache;
}
答案 0 :(得分:0)
弄清楚。 EF Core维护自己的IoC容器。 因此,您需要将现有服务传递到其容器中。
我不得不做下一件事。希望它可以帮助别人。
services.AddEntityFrameworkSqlServer();
services.Replace(new ServiceDescriptor(typeof(IQueryCompiler), typeof(CustomQueryCompiler), ServiceLifetime.Transient));
services.AddDbContext < AppDbContext > (options => {
options.UseSqlServer(Configuration.GetConnectionString("Default"));
options.UseInternalServiceProvider(services.BuildServiceProvider());
});