Hello I'm trying to instantiate a class on application startup and then share that instance through dependency injection to a controller. For some reason it won't let me use a Controller Constructor with parameters. It gives the errors:
[MissingMethodException: No parameterless constructor defined for this object.]
and
[InvalidOperationException: An error occurred when trying to create a controller of type 'Project1.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
I've found a couple of people who have had similar issues but I haven't been able to figure out what the exact problem is.
I also left out some of the extraneous code (why it doesn't look like the code actually does anything useful).
Startup.cs
using Project1.Services;
[assembly: OwinStartup(typeof(Project1.Startup))]
namespace Project1
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IPackageScraperService>(new PackageScraperService());
}
public void Configuration(IAppBuilder app)
{
}
}
}
IPackageScraperService.cs
using Project1.Services;
namespace Project1.Services
{
public interface IPackageScraperService
{
List<PackageScraperService.Script> GetLoadedScripts();
}
}
PackageScraperService.cs
namespace Project1.Services
{
public class PackageScraperService : Services.IPackageScraperService
{
public class Script
{
public FileAttributes Attibutes { get; set; }
public string Text { get; set; }
}
public List<Script> Scripts;
public List<Script> GetLoadedScripts()
{
return Scripts;
}
}
HomeController.cs
using Project1.Services;
namespace Project1.Controllers
{
public class HomeController : Controller
{
private IPackageScraperService _packageScraperService;
public HomeController(IPackageScraperService packageScraperService)
{
_packageScraperService = packageScraperService;
}
public ActionResult Index()
{
return View();
}
}
}
For anyone else looking for documentation, this tutorial worked for me.
http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/