0

The controller action method is not been called while using the constructor.

Here is the startup class.

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

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

        var connection = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<EmakitiContext>(options => options.UseSqlServer(connection));

        // Add framework services.
        services.AddMvc();
        services.AddTransient<IMarketUOW<EmakitiContext>, MarketUow<EmakitiContext>> ();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

When I added a constructor on the Homecontroller the action method is not been called.However, if I remove the constructor then the action method will be called. What I am doing wrong I am not able to figure it out.

Here is the controller

[Route("api/[controller]/[Action]")]
    public class HomeController : Controller
    {

        private readonly IMarketUOW<EmakitiContext> _iMarketUow;

        public HomeController(IMarketUOW<EmakitiContext> iMarketUow )
        {
            _iMarketUow = iMarketUow;
        }

        [HttpGet]
        public GenericResponseObject<List<MarketViewModel>> GetMarketList()
        {
            GenericResponseObject<List<MarketViewModel>> genericResponseObject = new GenericResponseObject<List<MarketViewModel>>();
            genericResponseObject.IsSuccess = false;
            genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionFailed;
            try
            {
                genericResponseObject.Data = _iMarketUow.GetMarketList();
                genericResponseObject.IsSuccess = true;
                genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionSuccess;
            }
            catch (Exception exception)
            {

            }
            return genericResponseObject;
        }


    }
}

Here is the Market Interface Class

 public interface IMarketUOW<C> where C: DbContext
    {
        List<MarketViewModel> GetMarketList();
    }

Here is the marketuow implement class

public class MarketUow<C> : IMarketUOW<C> where C : DbContext
    {

        private readonly IGenericRepository<C, Market> _iGenericRepository;

        public MarketUow(IGenericRepository<C, Market> iGenericRepository)
        {
            _iGenericRepository = iGenericRepository;
        }

        public List<MarketViewModel> GetMarketList()
        {
            List<MarketViewModel> listMarket = new List<MarketViewModel>();
            var databaseList = _iGenericRepository.GetAll().ToList();
            databaseList.ForEach(m => listMarket.Add(new MarketViewModel
            {
                MarketId = m.MarketId,
                City = m.City,
                CityF = m.CityF,
                IsActive = m.IsActive,
                Name = m.Name,
                NameF = m.NameF,
                SortOrder = m.SortOrder
            }));
            return listMarket;

        }

    }

Here is the Generic Interface code

public interface IGenericRepository<C,T> where C: DbContext where T : class
    {
        IQueryable<T> GetAll();
        IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate);

        void Add(T entity);
        void Delete(T entity);
        void Edit(T entity);
        void Save();

    }

Here is the Generic Implementation class

public abstract class GenericRepository<C,T> : IGenericRepository<C, T> where T: class where C: DbContext, new()
    {
        private C _entities =new C();
        public C Context
        {

            get { return _entities; }
            set { _entities = value; }
        }       

        public virtual IQueryable<T> GetAll()
        {

            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {

            IQueryable<T> query = _entities.Set<T>().Where(predicate);
            return query;
        }

        public virtual void Add(T entity)
        {
            _entities.Set<T>().Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
        }

        public virtual void Edit(T entity)
        {
            _entities.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Save()
        {
            _entities.SaveChanges();
        }
    }
2
  • Please add template of MarketUow class in question as well. Commented Dec 22, 2016 at 7:52
  • @Ahmar - I have updated the complete code. Please let me know Commented Dec 22, 2016 at 11:08

2 Answers 2

3

Home controller only initialize when its all dependency fulfill. Dependency Injunction try to instantiate MarketUow which depend on GenericRepository. Then it try to instantiate it but not able to do this because it abstract class.

Add this in startup

services.AddTransient< IGenericRepository< EmakitiContext,Market>, GenericRepository<EmakitiContext, Market>>();
services.AddTransient<IMarketUOW<EmakitiContext>, MarketUow<EmakitiContext>>();

and remove abstract modifier from GenericRepository and it will run.

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

Comments

0

You are actually missing to tell how to manage the dependency injection for IMarketUOW<EmakitiContext> interface.

In Startup.cs in ConfigureServices you have to add:

services.AddTransient<IMarketUOW, MarketUow>();
services.AddScoped(typeof(IMarketUOW<>), typeof(MarketUow<>));

6 Comments

I added in startup.cs but still same problem
As you said that without the controller it was working, I'm pretty sure it's a dependency injection issue and ASP does not know how to instantiate your controller with the parameter. I will have a closer look
I have updated the startup.cs file please let me know
Could you try just with: services.AddTransient<typeof(IMarketUOW<>), typeof(MarketUow<>)> ();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.