Unable to resolve service for type while attempting to activate

后端 未结 7 941
春和景丽
春和景丽 2020-12-09 02:22

I have one file Repository.cs that contains an interface and its implementation like so:

public interface IRepository

{
    IEnumerable

        
7条回答
  •  感情败类
    2020-12-09 02:43

    A method like this needs to be added to your Startup:

        // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //...
    
        // Add application services.
        services.AddTransient();
    
        //..
    }
    

    Services should be registered before used.

    UPDATE: If you do not want to use DI on your application, just create and instance of MemoryRepository on the constructor of HomeController, like this:

    public class HomeController : Controller
        {
            private IRepository repository;
    
            public HomeController()
            {
                repository = new MemoryRepository();
            }
    
            public IActionResult Index()
            {
                return View(repository.Cities);
            }
    
        }
    

提交回复
热议问题