siyavash
siyavash

Reputation: 178

InvalidOperationException: Unable to resolve service for type 'Repository.UnitOfWork'

this is my code in .net core 3.1 to implement repository unitofwork and generic. I write repository,user repository, unitofwork, contex and so. after run the app there is an error : InvalidOperationException: Unable to resolve service for type 'Repository.UnitOfWork'

I dont know what should I pass to the context or unitofwork as 'DbContextOptions'

this is my controller:

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        UnitOfWork db;
        public HomeController(ILogger<HomeController> logger, UnitOfWork db)
        {
            _logger = logger;
            this.db = db;
        }
}

this is my context:

public PandanetContext(DbContextOptions<PandanetContext> options) : base(options)
        {
        }

this is my unit of work:

 public class UnitOfWork : IDisposable
    {
        PandanetContext db;
        public UnitOfWork(PandanetContext db)
        {
            this.db = db;
        }
        private UserRepository userRepository;
        public UserRepository UserRepository
        {
            get
            {
                if (userRepository == null)
                {
                    userRepository = new UserRepository(db);
                }
                return userRepository;
            }
        }
}

this is my Repository:

public class UserRepository : Repository<UserDomainModel>
    {
        PandanetContext db;
        public UserRepository(PandanetContext context) : base(context)
        {
            db = context;
        }
    }

this is actionResult :

  public IActionResult Index()
        {            
            UserDomainModel user = new UserDomainModel();
            user.Name = "تست";
            db.UserRepository.create(user);
            db.UserRepository.Save();
            return View();
        }

in startup.cs:

services.AddDbContext<PandanetContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Upvotes: 1

Views: 936

Answers (1)

Stefan
Stefan

Reputation: 17658

You need to register the UnitOfWork:

In your startup.cs you can add the UnitOfWork to the services provider:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<UnitOfWork>();
 
    //... etc.
}

Upvotes: 1

Related Questions