.net core 7.0 依赖注入到类库

huangapple go评论60阅读模式
英文:

.net core 7.0 dependency injection to class library

问题

I'm trying to implement dependency injection by passing my connection strings from my .net core api to my class library (that contains dal and business logic) but i'm not sure how to proceed. So below i have in json:

"ConnectionStrings": {
        "con1": "Data Source=...",
        "con2": "Server=..."
}

in my core project

public class ConnectionStrings
{
    public string con1 { get; set; }
    public string con2 { get; set; }
}

and my program.cs

builder.Services.Configure<ConnectionStrings> (builder.Configuration.GetSection("ConnectionStrings"));
builder.Services.AddScoped<ConnectionStrings>();

Now to my Library. I have created a connection string class to contain my connection strings below

public class ConnectionStrings
{
    public string con1 { get; set; }
    public string con2 { get; set; }
}

And my Dal i have the following declaration

using mylibrary.Entities;
using System.Data;
using Dapper;
using System.Data.SqlClient;
using Microsoft.Extensions.Options;

namespace mylibrary.DataAccess
{
    public class MyprojectDAL
    {
        private readonly ConnectionStrings connectionString;

        public myprojectDAL(IOptions<ConnectionStrings> connectionString)
        {
            this.connectionString = connectionString.Value;
        }

        public MyprojectDAL()
        {
        }

        public MyProjectClass RetrieveDetails(int bid)
        {
            MyProjectClass bookieData = new MyProjectClass();

            using (IDbConnection cnn = new SqlConnection(connectionString.con1))
            ... implementation below call db with dapper etc...

Is this setup correctly and will work up till now?
Now my controller i create an instance of my business logic class, which then creates an instance of my data access layer class as below.

//controller

public ActionResult Get(int bid)
         {
            BusinessLogicLayer businessLogicLayer = new();
            if (bid > 0)
            {
                return Ok(businessLogicLayer.RetrieveDetails(bid));
            }

//businesss logic layer

public class businessLogicLayer
{
    public readonly MyprojectDAL _myprojectDAL = new MyprojectDAL();

    public MyProjectClass RetrieveDetails(int bid)
    {
        if (bid > 0)
        {
            MyProjectClass myProjectClass = _myprojectDAL.RetrieveDetails(bid);
            ....

The problem i have is when i try to run this i get a null reference exception because my connection string.con1 object is null so my connectionstring object isn't getting injected into my dal.

Now if i remove the public MyprojectDAL() {} default constructor i get an error in my business logic layer "there is no argument specified that corresponds to the paramater connectionstring of MyProjectDal(<Ioptions)"

So how do i go about resolving this? Do i need to apply interfaces between the layers or rethink how the dependency injection is setup? I've spent a while time trying to figure this out but can't really get to grips with it including the practical aspects of dependency injection. I think getting this working in something similar to my current setup would help me. Thanks for any input you may have.

英文:

I'm trying to implement dependency injection by passing my connection strings from my .net core api to my class library (that contains dal and business logic) but i'm not sure how to proceed. So below i have in json:

&quot;ConnectionStrings&quot;: {
        &quot;con1&quot;: &quot;Data Source=...&quot;,
        &quot;con2&quot;: &quot;Server=...&quot;       }

in my core project

public class ConnectionStrings
    {
        public string con1 { get; set; }
        public string con2 { get; set; }
    }

and my program.cs

builder.Services.Configure&lt;ConnectionStrings&gt; (builder.Configuration.GetSection(&quot;ConnectionStrings&quot;));
builder.Services.AddScoped&lt;ConnectionStrings&gt;();

Now to my Library. I have created a connection string class to contain my connection strings below

public class ConnectionStrings
    {
        public string con1 { get; set; }
        public string con2 { get; set; }
    }

And my Dal i have the following declaration

using mylibrary.Entities;
using System.Data;
using Dapper;
using System.Data.SqlClient;
using Microsoft.Extensions.Options;    

namespace mylibrary.DataAccess
{
    public class MyprojectDAL
    {
        private readonly ConnectionStrings connectionString;

        public myprojectDAL(IOptions&lt;ConnectionStrings&gt; connectionString)
        {
            this.connectionString = connectionString.Value;
        }

        public MyprojectDAL()
        {
        }

        public MyProjectClass RetrieveDetails(int bid)
        {
            MyProjectClass bookieData = new MyProjectClass();

            using (IDbConnection cnn = new SqlConnection(connectionString.con1))
            ... implementation below call db with dapper etc...

Is this setup correctly and will work up till now?
Now my controller i create an instance of my business logic class, which then creates an instance of my data access layer class as below.

 //controller
 public ActionResult Get(int bid)
         {
            BusinessLogicLayer businessLogicLayer = new();
            if (bid &gt; 0)
            {
                return Ok(businessLogicLayer.RetrieveDetails(bid));
            }

//businesss logic layer
public class businessLogicLayer
{
    public readonly MyprojectDAL _myprojectDAL = new MyprojectDAL();

    public MyProjectClass RetrieveDetails(int bid)
    {
        if (bid &gt; 0)
        {
            MyProjectClass myProjectClass = _myprojectDAL.RetrieveDetails(bid);
            .....

The problem i have is when i try to run this i get a null reference exception because my connection string.con1 object is null so my connectionstring object isn't getting injected into my dal.

Now if i remove the public MyprojectDAL() {} default constructor i get an error in my business logic layer "there is no argument specified that corresponds to the paramater connectionstring of MyProjectDal(<Ioptions<connectionstrings>)"

So how do i go about resolving this? Do i need to apply interfaces between the layers or rethink how the dependency injection is setup? I've spent a while time trying to figure this out but can't really get to grips with it including the practical aspects of dependency injection. I think getting this working in something similar to my current setup would help me. Thanks for any input you may have.

答案1

得分: 1

在我的观点中,您可以将DalbusinessLogicLayer注册到依赖注入容器中,然后通过依赖注入来使用它们,请参考这个简单的演示。

在我的解决方案中有两个项目(Web和类库),我在Web项目中配置了连接字符串:

"ConnectionStrings": {
    "con1": "aaaaaaaaaaaaaaaaaa",
    "con2": "bbbbbbbbbbbbbbbbbb"
}

然后在类库中创建一个模型:

public class ConnectionStrings
{
    public string con1 { get; set; }
    public string con2 { get; set; }
}

DAl:

public class Class1
{
    private readonly IOptions<ConnectionStrings> _ioption;

    public Class1(IOptions<ConnectionStrings> ioption)
    {
        _ioption = ioption;
    }

    public string getname()
    {
        return _ioption.Value.con1;
    }
}

businessLogicLayer

public class businessLogicLayer
{
    //在这里将DAL注入到businessLogicLayer
    private readonly Class1 _class;

    public businessLogicLayer(Class1 class1)
    {
        _class = class1;
    }

    public string Getname()
    {
        return _class.getname();
    }
}

在Web应用程序中,我将connectionStrings的JSON映射到connectionStrings模型并注册了DAL和businessLogicLayer:

builder.Services.Configure<ConnectionStrings>(builder.Configuration.GetSection("ConnectionStrings"));
builder.Services.AddScoped<Class1>();
builder.Services.AddScoped<businessLogicLayer>();

最后,在Web项目中,注入connectionStrings并调用其函数:

private readonly businessLogicLayer _businessLogicLayer;

public HomeController(businessLogicLayer businessLogicLayer)
{
    _businessLogicLayer = businessLogicLayer;
}

public IActionResult Privacy()
{
    var a = _businessLogicLayer.Getname();

    return OK();
}

现在它可以成功调用该函数并获取值。

英文:

In my opinion, You can register your Dal and businessLogicLayer into DI container, Then use them via dependency inject, Please refer to this simple demo.

Here I have two projects(Web and class library) in my solution, I configure connectionStrings in my web project:

&quot;ConnectionStrings&quot;: {
    &quot;con1&quot;: &quot;aaaaaaaaaaaaaaaaaa&quot;,
    &quot;con2&quot;: &quot;bbbbbbbbbbbbbbbbbb&quot;
  }

Then i create a model in class library:

public class ConnectionStrings
    {
        public string con1 { get; set; }
        public string con2 { get; set; }
    }

DAl:

public class Class1
    {
        private readonly IOptions&lt;ConnectionStrings&gt; _ioption;

        public Class1(IOptions&lt;ConnectionStrings&gt; ioption)
        {
            _ioption = ioption;
        }

        public string getname()
        {
            return _ioption.Value.con1;
        }

    }

businessLogicLayer

 public class businessLogicLayer
    {
        
        //Here I inject DAL into businessLogicLayer
        private readonly Class1 _class;

        public businessLogicLayer(Class1 class1)
        {
            
            _class = class1;
            
        }

        public string Getname()
        {
            return  _class.getname();
        }
    }

In web app, I map the connectionStrings json to connectionStrings model and register DAL and businessLogicLayer

builder.Services.Configure&lt;ConnectionStrings(builder.Configuration.GetSection(&quot;ConnectionStrings&quot;));
builder.Services.AddScoped&lt;Class1&gt;();
builder.Services.AddScoped&lt;businessLogicLayer&gt;();

Finally, In web project, Inject connectionStrings and call its function:

private readonly businessLogicLayer _businessLogicLayer;

    public HomeController(businessLogicLayer businessLogicLayer)
    {
        _businessLogicLayer = businessLogicLayer;
    }


    public IActionResult Privacy()
    {
          var a = _businessLogicLayer.Getname();

          return OK();
    }

Now it can successfully call the function and get the value:

.net core 7.0 依赖注入到类库

huangapple
  • 本文由 发表于 2023年2月23日 19:14:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定