c# – 使用Autofac的.NET Core(MYSQL)通用存储库自动连接

c# – 使用Autofac的.NET Core(MYSQL)通用存储库自动连接,第1张

概述我的目标是以下内容.我正在尝试使用以下方法设置新的解决方案: MySQL,.NET Core,Autofac,EF Core ……利用(通用)存储库模式. Ultimately I’ll be jumping onto a project with an existing db, thus my aim is to somehow make use of (t4) templates & EF t 我的目标是以下内容.我正在尝试使用以下方法设置新的解决方案: MySQL,.NET Core,autofac,EF Core ……利用(通用)存储库模式.

ultimately I’ll be jumPing onto a project with an existing db,thus my aim is to somehow make use of (t4) templates & EF to generate some of the models,then it “should” (famous last words) be as easy as making a repo for each model I need to interact with. (Each repo will just be a small lightweight class inherits the base)

Startup.cs

public class Startup{    public Startup(IHostingEnvironment env)    {        var builder = new ConfigurationBuilder()            .SetBasePath(env.ContentRootPath)            .AddJsonfile("appsettings.Json",optional: true,reloadOnChange: true)            .AddJsonfile($"appsettings.{env.Environmentname}.Json",optional: true)            .AddEnvironmentvariables();        this.Configuration = builder.Build();    }    public IConfigurationRoot Configuration { get; private set; }    // This method gets called by the runtime.     // Use this method to add services to the container.    public voID ConfigureServices(IServiceCollection services)    {        services.AddMvc();        services.            .AddDbContext<MyContext>(o => o.UseMysqL(          Configuration.GetConnectionString("MyConnection")));    }    public voID ConfigureContainer(ContainerBuilder builder)    {                       builder.RegisterGeneric(typeof(Repository<>))            .As(typeof(IRepository<>))            .InstancePerlifetimeScope();       // the below works (before adding the repos)       builder.RegisterassemblyTypes(AppDomain.CurrentDomain.GetAssemblIEs())           .Assignableto<IService>()           .AsImplementedInterfaces()           .InstancePerlifetimeScope();    }}

(Generic)Repository.cs

public abstract class Repository<T> : IRepository<T>    where T : class{    private Readonly MyContext _context;    protected Repository(MyContext context)    {        _context = context;    }    public virtual string Add(T entity)    {        if (ValIDateAdd(ref entity,out var message))        {            _context.Set<T>().Add(entity);        }        return message;    }    public virtual bool ValIDateAdd(ref T entity,out string message)    {        message = default(string);         return true;    }}

存储库的实现:

FooRepository.cs

// public interface IFooRepository: IRepository<Foo>public class FooRepository: Repository<Foo>,IFooRepository{    public FooRepository(MyContext context) : base(context)    {    }    public overrIDe bool ValIDateAdd(ref Foo entity,out string message)    {        // just a hook for pre-insert stuff        message = "All foos shall fail add";        return false;    }}

然后在服务或控制器中使用,或者你有什么.

FooService.cs

public class FooService: IFooService{    private Readonly IFooRepository _repository;    public FooService(IFooRepository repository)    {        _repository = repository;    }    public voID DoSomethingThenAdd()    {       // some other business logic specific to this service        _repository.Add(new Foo()        {            ID = 1,Lastname = "bar",name = "Foo"        });    }}

问题:

我如何解决所有这些问题……我一直在努力寻找关于MysqL Ef的正确文档,而且我有点觉得那部分是“正常工作”.但正如您在下面的错误日志中所看到的那样,我对存储库的注册搞砸了.

错误:

An error occurred during the activation of a particular registration.

See the inner exception for details.

Registration: Activator = FooService (ReflectionActivator),Services
= [MyApp.Services.Interfaces.IFooService,MyApp.Services.Interfaces.IService],lifetime =
autofac.Core.lifetime.CurrentScopelifetime,Sharing = Shared,
Ownership = OwnedBylifetimeScope

—> None of the constructors found with ‘autofac.Core.Activators.Reflection.DefaultConstructorFinder’ on type
‘MyApp.Services.FooService’ can be invoked with the available
services and parameters:

Cannot resolve parameter ‘MyApp.Data.Interfaces.IFooRepository
repository’ of constructor ‘VoID
.ctor(MyApp.Data.Interfaces.IFooRepository)’. (See inner exception
for details.)

–> autofac.Core.DependencyResolutionException: None of the constructors found with
‘autofac.Core.Activators.Reflection.DefaultConstructorFinder’ on type
‘MyApp.Services.FooService’ can be invoked with the available
services and parameters:

Cannot resolve parameter ‘MyApp.Data.Interfaces.IFooRepository
repository’ of constructor ‘VoID
.ctor(MyApp.Data.Interfaces.IFooRepository)’.

解决方法 以下行将注册Repository< Foo>作为IRepository< Foo>在autofac中:

builder.RegisterGeneric(typeof(Repository<>))       .As(typeof(IRepository<>))       .InstancePerlifetimeScope();

但是IRepository< Foo>不是IFooRepository,FooService需要IFooRepository.这就是为什么autofac失败并出现以下错误消息:

Cannot resolve parameter ‘MyApp.Data.Interfaces.IFooRepository repository’ of constructor ‘VoID .ctor(MyApp.Data.Interfaces.IFooRepository)’.

如果你想保留你的FooRepository和IFooRepository,你必须注册它们:

builder.RegisterType<FooRepository>()       .As<IFooRepository>()

另一种解决方案是注册IRepository<>的所有实现.

builder.RegisterassemblyTypes(AppDomain.CurrentDomain.GetAssemblIEs())       .AsClosedTypesOf(typeof(IRepository<>))

和FooService应该依赖于Irepository< Foo>而不是IFooRepository

public class FooService: IFooService{    private Readonly IRepository<Foo> _repository;    public FooService(IRepository<Foo> repository)    {        this._repository = repository;    }    // ...}

当您使用IIS:Assembly scanning – IIS Hosted application时,请小心使用程序集扫描

总结

以上是内存溢出为你收集整理的c# – 使用Autofac的.NET Core(MYSQL)通用存储库自动连接全部内容,希望文章能够帮你解决c# – 使用Autofac的.NET Core(MYSQL)通用存储库自动连接所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1239751.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存