依赖注入的ASP.NET Core多重实现

编程入门 行业动态 更新时间:2024-10-10 18:27:21
本文介绍了依赖注入的ASP.NET Core多重实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有一种方法可以使用ASP.NET Core指定单个接口的多个实现?我可以在Ninject中这样做:

Is there a way I can designate multiple implementations of a single interface using ASP.NET Core? I could do this in Ninject like this:

ninjectKernel.Bind<DbContext>().To<OracleDbContext>().Named("UnitWork"); ninjectKernel.Bind<DbContext>().To<AppsDbContext>().Named("AppsWork");

推荐答案

如果您的问题仅针对 DbContext ,那么使用以下语句很容易

If your question is specific to just DbContext then it's easy using the following statements

public void ConfigureServices(IServiceCollection services) { services.AddDbContext<OracleDbContext>(builder => builder.UseSqlServer(connectionString)); services.AddDbContext<AppsDbContext>(builder => builder.UseSqlServer(connectionString)); }

如果您的问题与通用接口有关,那么只有当它是通用接口时才有可能.假设您有一个如下所示的界面:

If your question relates to general interfaces, then it's possible only if it's a generic interface. Say you have an interface like below:

public interface IRepository<T> { }

以及多种实现方式,例如:

And multiple implementations like:

public class GenericRepository<User> : IRepository<User> { } public class GenericRepository<Order> : IRepository<Order> { }

您只需要一行就可以注册多个实现.

You only need a single line to register multiple implementations.

public void ConfigureServices(IServiceCollection services) { // you can register them with any life time like that e.g. Singleton, Transient services.AddScoped(typeof(IRepository<>), typeof(GenericRepository<>)); }

我希望这对您有帮助

更多推荐

依赖注入的ASP.NET Core多重实现

本文发布于:2023-11-06 01:57:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!