MVC:No parameterless constructor defined for this object - asp.net-mvc

Server Error in '/' Application.
No parameterless constructor defined for this object.How can I resolve this issue.
I created one folder in that created interface ICompanyService and class CompanyService.
Controller:
public class HomeController : Controller
{
private ICompanyService icompanyService;
public HomeController(ICompanyService icompanyService)
{
this.icompanyService = icompanyService;
}
public ActionResult Index()
{
ViewBag.CompanyName = this.icompanyService.GetCompany();
return View();
}
}
ICompanyService:
public interface ICompanyService
{
string GetCompany();
}
CompanyService:
public class CompanyService
{
public string GetCompany()
{
return "Msc";
}
}

You need to include below constructor to your controller,
public HomeController() : this(new CompanyService())
{
}
So your entire controller code looks like below,
public class HomeController : Controller
{
private ICompanyService icompanyService;
public HomeController() : this(new CompanyService())
{
}
public HomeController(ICompanyService icompanyService)
{
this.icompanyService = icompanyService;
}
public ActionResult Index()
{
ViewBag.CompanyName = this.icompanyService.GetCompany();
return View();
}
}
This will solve your issue.
Happy coding!!!!!

CompanyService Class Should Inherits From ICompanyService Interface.
Please Study About Dependency Injection In .NET .
public class CompanyService : ICompanyService
{
public string GetCompany()
{
return "Msc";
}
}

#ravi please use dependency injection, so what service will automatically initialize your service constructor without defined constructor logic, the dependency inject handle and initialize you service object. don't worry about initialization.
below i have mention the link for IoC and i hope your issue will resolve soon.
https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc

Related

No parameterless constructor defined for this object error in asp .net MVC

hello guys I have problem with this error. my project is simple I have an Interface called "IApiService" and I have a class called Api that is relative with my IApiService Interface. So in "Api" I have a method that post an api and I think this error doesn't relative with my error. I think error is in my Controller. So I will put my controller code so you guys could help me with!
Here it is:
public class HomeController : Controller
{
IApiService _apiService;
public HomeController(IApiService apiService)
{
_apiService = apiService;
}
// GET: Home
public async Task<ActionResult> Index(CheckOutViewModel model)
{
var result = await _apiService.CheckOut(model);
return View();
}
}
For asp.net framework:
The difference is that you should have your controller like this, no need to inject dependency:
public class HomeController : Controller
{
IApiService _apiService;
public HomeController() : this(new ApiService())
{
}
public HomeController(IApiService apiService)
{
_apiService = apiService;
}
public string getString(string name) {
string a = _apiService.CheckOut(name);
return a;
}
}
==============================================
Please allow me to show a sample here, asp.net core.
My Controller:
public class HomeController : Controller
{
private readonly IApiService _apiService;
public HomeController( IApiService iapiService)
{
_apiService = iapiService;
}
public string getString(string name) {
string a = _apiService.CheckOut(name);
return a;
}
}
My interface:
namespace WebMvcApp.Services
{
public interface IApiService
{
public string CheckOut(string str);
}
}
My implement of the interface:
namespace WebMvcApp.Services
{
public class ApiService: IApiService
{
public string CheckOut(string str)
{
return "hello : " + str;
}
}
}
I inject the dependency in startup.cs -> ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<IApiService, ApiService>();
}
or in .net 6 in Program.cs file:
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IApiService, ApiService>();

Unity how to pass Request in Controller's constructor from Unity

The old controller code with Concrete dependencies:
public SomeController: Controller
{
public SomeController()
{
}
public ActionResult Default()
{
**Something something = new Something(Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString());**
something.SomeMethod();
}
}
The new Controller code with TDD focus:
public SomeControllerNew: Controller
{
private readonly ISomething _something;
public SomeControllerNew(ISomething something)
{
_something = something;
}
public ActionResult Default()
{
_something.SomeMethod();
}
}
PROBLEM:
Now in new TDD approach i need to invoke constructor where I am registering the Interface. I have put it in UnityBootstraper common file, Something like:
var container = new UnityContainer();
container.RegisterType();
**Something something = new Something(Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString());**
something.SomeMethod();
This is not working here. Error is quite clear:
Object reference required for non-static field, method, property 'System.Web.Mvc.Controller.Request.get'.
I can't figure out how i can access http request here in UnityBootstrapper?
Edit:
Trying to do all this in RegisterRoutes.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
DependencyResolver.SetResolver(new Unity.Mvc3.UnityDependencyResolver(UnityBootstrapper.Initialise()));
var container = new UnityContainer();
container.RegisterType<ISometing, Something>();
}
}
One way to do it is to create an abstract factory like this:
public interface ISomethingFactory
{
ISomething Create(string url);
}
public class SomethingFactory : ISomethingFactory
{
public ISomething Create(string url)
{
return new Something(url);
}
}
And make your controller depend on it like this:
public class SomeControllerNew: Controller
{
private readonly ISomething _something;
public SomeControllerNew(ISomethingFactory somethingFactory)
{
_something = somethingFactory.Create(Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString();
}
public ActionResult Default()
{
_something.SomeMethod();
}
}
A better approach (IMO) is to use a custom Controller Factory instead of using the Dependency Resolver like this:
public class CustomFactory : DefaultControllerFactory
{
public override IController CreateController(RequestContext requestContext, string controllerName)
{
var request = requestContext.HttpContext.Request; //Here we have access to the request
if (controllerName == "Some") //Name of controller
{
//Use the container to resolve and return the controller.
//When you resolve, you can use ParameterOverride to specify the value of the string dependency that you need to inject into Something
}
return base.CreateController(requestContext, controllerName);
}
}
This way you don't have to introduce the ISomethingFactory, and your controller would still depend on ISomething directly.
You would need to tell the MVC framework about this custom controller factory like this (in Application_Start):
ControllerBuilder.Current.SetControllerFactory(new CustomFactory());

Can i have a baseController that has all my repositories when using StructureMap?

Historically my controllers have repositories declared on each controller which are injected through StructureMap and this is working fine for me.
But my new project will likely be using the same repositories for each controller.
Due to this i created a BaseController and inherit all controllers from here.
My repositories now live in Base but the injection is not working.
Can it work like this or does constructor injection have to take place on each controller?
public static void BootStructureMap()
{
ObjectFactory.Initialize(x =>
{
x.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.WithDefaultConventions();
scanner.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", "").ToLower());
});
x.For(typeof(IGenericRepository<>)).Use(typeof(GenericRepository<>));
});
}
Working:
public class TransactionController : Controller
{
public IGenericRepository<ITransaction> TransactionRepository { get; set; }
public TransactionController(IGenericRepository<ITransaction> transactionRepository)
{
this.TransactionRepository = transactionRepository;
}
public ActionResult Index()
{
var transactions = this.TransactionRepository.Query.AsEnumerable();
return View(transactions);
}
Not working:
public class BaseController : Controller
{
public IGenericRepository<ITransaction> TransactionRepository { get; set; }
public BaseController(IGenericRepository<ITransaction> transactionRepository)
{
this.TransactionRepository = transactionRepository;
}
protected BaseController()
{
}
}
public class TransactionController : BaseController
{
public ActionResult Index()
{
var transactions = base.TransactionRepository.Query.AsEnumerable();
return View(transactions);
}
}
You have to inject your repository into BaseController somehow. If your last piece of code is the real code you have then it seems that BaseController is initialized through protected parameterless constructor.
Add the constructor to TransactionController:
public TransactionController(IGenericRepository<ITransaction> transactionRepository) : base(transactionRepository)
{
}
Can use Poor Man's Dependency Injection - used in NerdDinner application
public BaseController() : this(new Message())
{
}
Or
Refer Phill's link
tdd-and-dependency-injection-with-asp.net-mvc.aspx
Override DefaultControllerFactory
public class SMControllarFactory : DefaultControllerFactory
In
application start
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(new SMControllarFactory());

Windsor container components not available on first controller action

I'm using a configuration within the global.asax.cs to register the components but it looks the container hasn't been initialized yet at the first http request (HomeController > Index action) and it gives me a "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection." error.
I can't find a solution for this and is driving me mad!
Extract of my global.asax.cs:
protected void Application_Start()
{
InitializeContainer();
InitializeDatabase();
RegisterRoutes(RouteTable.Routes);
}
private void InitializeContainer()
{
_container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container));
// Register context manager.
_container.Register(
Component.For<IContextManager>()
.ImplementedBy<CoursesContextManager>()
.LifeStyle.Singleton
.Parameters(
Parameter.ForKey("connectionString").Eq(ConfigurationManager.ConnectionStrings["CoursesConnection"].ConnectionString)
)
);
// Register specifc repository implementations (can we do this more generic?)
_container.Register(
Component.For<ICourseRepository>()
.ImplementedBy<CourseRepository>()
.LifeStyle.Singleton
);
[...other interfaces and controllers registered...]
}
Controller where the exception is thrown at first http request:
public class HomeController : Controller
{
private ICourseRepository _courseRepository;
public HomeController(ICourseRepository courseRepository)
{
_courseRepository = courseRepository;
}
public ActionResult Index()
{
var courses = _courseRepository.Find(); //here is where it fails
return View(courses);
}
}
Repository/interfaces:
Generic interface:
public interface IRepository<T>
{
IQueryable<T> Find();
}
Generic repository:
public class MyRepository<T> : IRepository<T> where T : class
{
private IContextManager _contextManager;
private string _qualifiedEntitySetName;
private string _keyName;
protected ObjectContext CurrentObjectContext
{
get { return _contextManager.GetContext(); }
}
protected ObjectSet<T> ObjectSet
{
get { return CurrentObjectContext.CreateObjectSet<T>(); }
}
public MyRepository(IContextManager contextManager)
{
this._contextManager = contextManager;
this._qualifiedEntitySetName = string.Format("{0}.{1}"
, this.ObjectSet.EntitySet.EntityContainer.Name
, this.ObjectSet.EntitySet.Name);
this._keyName = this.ObjectSet.EntitySet.ElementType.KeyMembers.Single().Name;
}
public IQueryable<T> Find()
{
return ObjectSet;
}
}
Interface course based on generic repository:
public interface ICourseRepository : IRepository<Course>
{
}
if you use Unit Of Work pattern you will solve your problem
Check this post Unit Of Work Pattern, is very usefull
I found a way to handle with this at least momentarily. Because the problem happens on the first request, I've just added another action in my controller and redirect the index action to it. Probably not the best solution but can't spend more time on this issue!
public class HomeController : Controller
{
private ICourseRepository _courseRepository;
public HomeController(ICourseRepository courseRepository)
{
_courseRepository = courseRepository;
}
public ActionResult Index() // Default action in the controller, first hit
{
return RedirectToAction("Home");
}
public ActionResult Home() //The repository is available here, no exception thrown
{
var courses = _courseRepository.Find(); //here is where it fails
return View(courses);
}
}

Ninject And Connection Strings

I am very new to Ninject and am trying Ninject 2 with MVC and Linq. I have a SqlProductRepository class and all I want to know is what's the best way of passing the connectionstring in the constructor if I am injecting the Repository object in the controller.
public class SqlProductRepository:IProductRepository
{
private Table<Product> productsTable;
public SqlProductRepository(string connectionString)
{
productsTable = (new DataContext(connectionString)).GetTable<Product>();
}
public IQueryable<Product> Products
{
get { return productsTable; }
}
}
This is my ProductController class where I am injecting the Repository:
public class ProductsController : Controller
{
private int pageSize = 4;
public int PageSize { get { return pageSize; } set { pageSize = value; } }
IProductRepository _productsRepository;
[Inject]
public ProductsController(IProductRepository productRepository)
{
_productsRepository = productRepository;
}
public ViewResult List(int page)
{
return View(_productsRepository.Products
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList()
);
}
}
Can somebody please guide me regarding this?
You can set it up in your binding
_kernel.Bind<IProductRepository>()
.To<SqlProductRepository>()
.WithConstructorArgument("connectionString",yourConnectionString );
You're doing:
new DataContext(connectionString)
in your code - this is the very newing and binding to classes you're trying to push out of your code by using a DI container. At the very least, consider adding an IConnectionStringSelector interface or something like that. You dont want to have 20 Bind calls for 20 repositories - you want a higher level abstraction than that.
I'd suggest the best solution is that you should be demanding either an IDataContext or an IDataContextFactory in the constructor instead and letting that worry about it.
You could supply the connection string as a constructor argument when binding the SqlProductRepository to the IProductRepository interface.
public class LinqToSqlModule : NinjectModule
{
public override void Load()
{
Bind<IProductRepository>().To<SqlProductRepository>()
.WithConstructorArgument(connectionString, "connectionstring");
}
}
I would suggest a slightly different approach. First of all, you might want to create a binding for the DataContext class in the kernel. You could do so by using a provider class to create your DataContext passing the connection string as an argument to its constructor. Then you bind the DataContext to the DataContextProvider.
public class DataContextProvider : Provider<DataContext>
{
protected override DataContext CreateInstance(IContext context)
{
string connectionString = "connectionstring";
return new DataContext(connectionString);
}
}
public class LinqToSqlModule : NinjectModule
{
public override void Load()
{
Bind<DataContext>().ToProvider<DataContextProvider>();
Bind<IProductRepository>().To<SqlProductRepository>();
}
}
Next modify the constructor of SqlProductRepository class to accept a DataContext object instead.
public class SqlProductRepository : IProductRepository
{
private readonly DataContext context;
public ProductRepository(DataContext context)
{
this.context = context;
}
public IQueryable<Product> Products
{
get { return context.GetTable<Product>(); }
}
}
By the way you don't have to decorate your constructor with the Inject attribute. Ninject will select the constructor with the most parameters by default.
Please refer below code snap:
//Bind the default connection string
public void BindDataContext()
{
ConstructorArgument parameter = new ConstructorArgument("connectionString", "[Config Value]");
Bind<DataContext>().ToSelf().InRequestScope().WithParameter(parameter);
}
//Re-Bind the connection string (in case of multi-tenant architecture)
public void ReBindDataContext(string cn)
{
ConstructorArgument parameter = new ConstructorArgument("connectionString", cn);
Rebind<DataContext>().ToSelf().InRequestScope().WithParameter(parameter);
}
For more information, please visit below link
MVC3, Ninject and Ninject.MVC3 problem

Resources