S
S
super152018-08-15 02:39:38
ASP.NET
super15, 2018-08-15 02:39:38

Why doesn't AddTransient() work in ASP.NET CORE 2.0?

There is an interface

using System;
namespace WebEmpty.Models
{
    public interface IProductRepository
    {
        IEnumerable<Product> Products { get; }
    }
}

And the class that implements it
using System;
namespace WebEmpty.Models
{
    public class FakeProductRepository : IProductRepository
    {
        public IEnumerable<Product> Products => new List<Product>
        {
            new Product { Name = "Football", Price = 25 },
            new Product { Name = "Surf board", Price = 179 },
            new Product { Name = "Running shoes", Price = 95 }
        };
    }
}

And also in the ConfigureServices method of the Startup.cs file, I added the line services.AddTransient<>();
public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IProductRepository, FakeProductRepository>();
            services.AddMvc();
        }

The web application works, but in the method of its controller the repository field is not filled with an instance of FakeProductRepository ()
public class ProductController : Controller
    {
        IProductRepository repository;
        public ProductController(IProductRepository repo)
        {
            repository = repo;
        }
        public ViewResult List() => View(repository.Products);
    }

The application is taken from Freeman's book "ASP.NET Core with Examples for Professionals", works for him, not for me. If it's due to version differences, then how do I fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor P., 2018-08-23
@Jeer

Hello, have you figured it out? It looks like everything should work, where was the mistake?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question