0

I am using .net core 3.1 and I have configured AppDbContext in the Web application. I have another class library project and inside I've added reference of Webapplication. How do I use Web App Dbcontext in the class library?

I tried creating instance of AppDbContext in class as below.

 public class CallService { private readonly IServiceProvider _service; private readonly AppDbContext _context; public CallService(AppDbContext context,IServiceProvider service) { _context = context; _service = service; } //... //... } 

But issue I am having is , Whenever I create instance of above class in Console Application, It requires me to pass 2 arguments. enter image description here

6
  • Errr, have tried injecting it ? Commented Sep 9, 2020 at 16:19
  • 1
    You need an instance of the class and pass the instance between projects. Commented Sep 9, 2020 at 16:19
  • @frz3993, No i have not. I am new to this so not sure how to do it. Commented Sep 9, 2020 at 16:21
  • @jdweng, Instance of AppDbcontext class? Commented Sep 9, 2020 at 16:28
  • You already have the instance of the class. You just need to pass the instance to other project. Isn't it _context Commented Sep 9, 2020 at 17:55

1 Answer 1

3

There are multiple problems in this code.

If you want to use the same code both in the console app and web you should extract it in a class library . After that you should add reference from web and console application to your class library.Adding reference from a console application to a web application is wrong.

To do it properly you should you use a dependency injection system.

First you will need to create a interface for your service. Then you can define another class in the class library project that will add all the dependencies from that class library.

public static class DomainModuleDependencies{ public static IServiceProvider AddDomainDependencies(this IServiceCollection services){ //... add any dependency here services.AddTransient<AppDbContext>(); services.AddTransient<ICallService,CallService>(); } } 

Then you can call the service provider to give you the service that you need

var services = new ServiceCollection(); services.AddDomainDependencies(); var serviceProvider = services.BuildServiceProvider(); var callService = services.GetService<ICallService>(); callServices.CallMethod(); 

Sounds complicated but in the future if you need to add another service you can just created and add it to dependencies. In this way you will follow as mutch as you can from SOLID.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.