两个ASP.NET Core项目之间的依赖关系注入 [英] Dependency injection between two ASP.NET Core projects

查看:60
本文介绍了两个ASP.NET Core项目之间的依赖关系注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用ASP.NET Core开发一个Web应用程序,并使用Entity Framework Core处理数据库.我的VS解决方案中有两个项目;WebApp(主应用程序)和DatabaseHandler(EF Core处理程序).因为我使用的是MySQL数据库,所以我已经将Entity Framework Core和Pomelo软件包一起安装了.

I'm currently developing a web application with ASP.NET Core and handling the database with Entity Framework Core. I have two projects in my VS Solution; WebApp (the main application) and DatabaseHandler (the EF Core handler). I have installed Entity Framework Core with the Pomelo package, since I'm using a MySQL database.

我一直在遵循Microsoft文档来设置EF Core,连接字符串等,并且一切正常.我能够进行迁移,进行更新以及对数据库进行处理.但是我不确定我是否做得正确,因为最新的EF Core教程使用了依赖注入,而我对此并不熟悉.

I've been following the Microsoft documentation to setup EF Core, connection strings and all that, and it works fine. I'm able to make migrations, make updates and do stuff with the database. I'm however not sure if I'm doing it correctly, since the latest EF Core tutorials use dependency injection and I'm not familiar with it.

现在,我要将DbContext对象作为参数从WebApp传递给DatabaseHandler,因为我希望所有与数据库相关的内容仅存在于DatabaseHandler中.这可行,但是是否可以从另一个项目中调用函数并共享DbContext对象而不将其作为参数传递呢?我可能没有很好地解释它,希望我的代码能更好地解释它.

Right now I'm passing the DbContext object as an argument from WebApp to DatabaseHandler, since I want all database-related stuff to only exist in DatabaseHandler. This works, but is it possible to call functions from another project and also share the DbContext object without passing it as an argument? I'm probably not explaining it well, I hope my code explains it better.

WebApp/Startup.cs:
这是我从appsettings.json加载连接字符串的地方.

WebApp/Startup.cs:
This is where I load the connection string from appsettings.json.

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<DataContext>(
        options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")
    ));

    services.AddRouting(options => options.LowercaseUrls = true);
    services.AddControllersWithViews();
}

WebApp/HomeController.cs:
在这里,我从DatabaseHandler项目调用GetAllChallenges()函数,并且还将DataContext对象作为参数传递.这就是我要避免的事情!

WebApp/HomeController.cs:
This is where I call the GetAllChallenges() function from the DatabaseHandler project, and I also pass the DataContext object as an argument. This is what I'm trying to avoid!

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly DataContext db;

    public HomeController(ILogger<HomeController> logger, DataContext _db)
    {
        _logger = logger;
        db = _db;
    }

    public IActionResult Challenges()
    {
        List<Challenge> ChallengesList = DatabaseHandler.HandleChallenges.GetAllChallenges(db);
        return View(ChallengesList);
    }
}

DatabaseHandler/DataContext.cs:
这是我初始化实体类的地方.

DatabaseHandler/DataContext.cs:
This is where I initialize the entity classes and so on.

public class DataContext : DbContext
{
    public DataContext(DbContextOptions<DataContext> options) : base(options) { }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }

    // Tables
    public DbSet<User> Users { get; set; }
    public DbSet<Challenge> Challenges { get; set; }

    // Data seeding
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Seed();
    }
}

DatabaseHandler/HandleChallenges.cs:
这是我所有数据库功能的所在地.结果返回到WebApp项目内的控制器.

DatabaseHandler/HandleChallenges.cs:
This is where I have all my database functions. The results are returned back to the controller within the WebApp project.

public class HandleChallenges
{
    public static List<Challenge> GetAllChallenges(DataContext db)
    {
        var Data = db.Challenges;
        List<Challenge> ChallengesList = Data.ToList();
        return ChallengesList;
    }
}

我已经研究了依赖注入,但是我不确定如何在两个项目之间使用它.是否有一种不太复杂的方法可以实现这一目标,也许根本不需要使用DI?我很满意,只要我不需要每次需要从DatabaseHandler调用函数时都将DataContext对象作为参数传递.

I have looked into dependency injection, but I'm not sure how I can use this between two projects. Is there a less complicated way of achieving this, perhaps without using DI at all? I'm satisfied as long as I don't need to pass the DataContext object as an argument every time I need to call a function from DatabaseHandler.

有人可以帮助我理解吗?提前非常感谢!

Can someone help me understand? Thanks a lot in advance!

推荐答案

您可以使用我已经使用过很多次的Options模式.尽管您使用的是数据库,但它的效果仍然很好.通过依赖注入,您可以从多个项目中进行访问.阅读有关选项模式的文档( https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1 )很有用,但我还将为您提供自己的示例:

You could use Options pattern, which I have already used many times. Its working very well despite of database you use. Thanks to dependency injection you are able to access if from multiple projects. Reading documentation about Option pattern (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1) is useful but I will also provide you with my own example :

  1. 首先创建一个模型来存储连接字符串,dbName等.请记住将其添加到主项目(例如Web Api)之外的库中:

  1. First you create model to store you connection string, dbName etc. Remember to add it in a library outside your main project(eg. Web Api) :

 public class NameOfYourProject_ApiDbSettings : IIMTTApiDbSettings
 {
     public NameOfYourProject_ApiDbSettings()
     {
     }
     public string CollectionName { get; set; }
     public string ConnectionString { get; set; }
     public string DatabaseName { get; set; }
 }


public interface I_NameOfYourProject_ApiDbSettings
{
 string CollectionName { get; set; }
 string ConnectionString { get; set; }
 string DatabaseName { get; set; }
}

  • 接下来,您可以将其用于所有项目:

  • Secondly you make it available for all you projects :

        services.Configure<NameOfYourProjectApiDbSettings>(options =>
         {
             options.ConnectionString
                 = Configuration.GetSection("NameOfYourProjectDbSettings:ConnectionString").Value;
             options.DatabaseName
                 = Configuration.GetSection("NameOfYourProjectDbSettings:DatabaseName").Value;
         });
    

  • 然后您可以在多个项目中使用它.(记住要为您的模型添加引用->点1.我将模型始终与存储库一起使用)我将为您提供使用MongoDb的示例:

  • Then you can use it in multiple projects. (Rememebr to add referance to you model -> point 1. I keep the model always with repository) I will give you my example where I use MongoDb :

     private readonly IMongoDatabase _database = null;
    
     public SomeObjectContext(IOptions<IMyProjectDbSettings> settings)
     {
         var client = new MongoClient(settings.Value.ConnectionString);
         if (client != null)
             _database = client.GetDatabase(settings.Value.DatabaseName);
     }
    
     public IMongoCollection<MyModel> MyModels
     {
         get
         {
             return _database.GetCollection<MyModel>("MyModels");
         }
     }
    

  • 这篇关于两个ASP.NET Core项目之间的依赖关系注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆