0
votes

I have a Dnn module project for a Web API. In the startup I want to configure dependency injection for this module.

The error I get is: "An error occurred when trying to create a controller of type 'SchoolsController'. Make sure that the controller has a parameterless public constructor."

Inner exception is a bit clearer on the actual problem: "Unable to resolve service for type 'MyProj.Persistence.Context.PortfolioContext' while attempting to activate 'MyProj.Persistence.UnitOfWork.UnitOfWork'."

My guess is that this is because my UnitOfWork class constructor requires a DbContext?

My unit-of-work class looks like this:

public class UnitOfWork: IUnitOfWork, IDisposable
{
    private readonly PortfolioContext context;

    public UnitOfWork(PortfolioContext context)
    {
        this.context = context;
        Schools = new SchoolRepository(context);
        Users = new UserRepository(context);
    }
}

My controller looks like this:

public class SchoolsController: BaseController
{
    private readonly IUnitOfWork unitOfWork;

    public SchoolsController(IUnitOfWork unitOfWork)
    {
        this.unitOfWork  = unitOfWork;
    }
} 

My startup class:

public class Startup : IDnnStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IUnitOfWork, UnitOfWork>();
    }
}

I've tried to add the DbContext before adding the scoped UnitOfWork like this, but it didn't work:

services.AddSingleton<DbContext, PortfolioContext>((ctx) =>
{
    return new PortfolioContext();
});

Any ideas how to do this in Dnn? Normally I would add the DBContext by doing something like this:

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  

But for some reason I cannot find the extension method AddDbContext anywhere in this context (Dnn, IDnnStartup, etc.)

EDIT:
Forgot to add that this is for Dnn 9.6.2 which targets .net 4.7.2

1
If it was API, isn't it supposed to reference from DNNApiController ?erw13n
@erw13n apologies, the BaseController that my controller inherits from actually inherits from DnnApiControllerJacques

1 Answers

0
votes

Turns out I wasn't far off.

Where I originally tried this:

services.AddSingleton<DbContext, PortfolioContext>((ctx) =>
{
    return new PortfolioContext();
});

Should have actually been this:

services.AddSingleton<PortfolioContext>((ctx) =>
{
    return new PortfolioContext();
});