I've created an injectable dbcontext
Startup.cs:
public void ConfigureServices(IServiceCollection services) { services.AddScoped<IUnitOfWork, UnitOfWork>(); services.AddDbContext<DBContext>(options => options.UseSqlServer("Server=localhost;Database=mydb;Trusted_Connection=True;")); } UnitOfWork:
public class UnitOfWork : IUnitOfWork { private readonly DBContext _context; public UnitOfWork(DBContext context) { _context = context; } The injection working fine in the controller:
public class UserController : ControllerBase { private readonly IUnitOfWork unitOfWork; public UserController(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } } How can I create custom class that takes IUnitOfWork in the constructor and call it from main program?
CustomClass :
public class CustomClass { private readonly IUnitOfWork unitOfWork; public CustomClass(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } } Main program:
public class Program { public static void Main(string[] args) { var unitOfWork=new UnitOfWork() // Here I don't want to pass new DBContext I want to reach the same injected DBContext var customClass =new CustomClass (unitOfWork); } }
public CustomClass(IUnitOfWork unitOfWork)and then useunitOfWorkin that Class.Startup.csfile with theConfigureServices()method from yourMain()method?