Stuart Lexington
Stuart Lexington

Reputation: 71

Correct way to connect controllers using Dependency Injection

If i have a controller that receives and processes the action selected by the user, and then want to use another controller to store all database related logic, what is the correct way to connect these controllers while allowing the 2nd controller to interact with the database context.

At the moment I have it working with creating a database context in the first controller and then parsing that to the database controller when I connect the two using DI, but hopefully someone could show me the correct way to do this.

  public class TestController : Controller
{
    private readonly DatabaseContext context;
    private Database.UserController userDatabaseController;

    public TestController(DatabaseContext db)
    {
        context = db;
        userDatabaseController = new Database.UserController(context);
    }

}

database controller

public class UserController : Controller
{
    private readonly DatabaseContext context;

    public UserController(DatabaseContext ctx)
    {
        context = ctx;
    }
    public bool RegisterUser(Models.DatabaseModels.UserModel model)
    {
        try
        {
            context.Users.Add(model);
            context.SaveChanges();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }

    }
}

startup.cs

  services.AddDbContext<DatabaseContext>
            (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

databasecontext

 public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options)
       : base(options)
    { }
    public DbSet<DatabaseModels.UserModel> Users { get; set; }
}

Upvotes: 0

Views: 122

Answers (2)

Arcanox
Arcanox

Reputation: 1547

If you're finding that you need to call Controller methods from another Controller, you probably need to refactor your code. Controllers should have very little logic in them, which usually just involves calling a Service layer and then constructing a ViewModel from the data.

My advice would be to do some reading on the Service Layer pattern and the Repository pattern (sometimes called the Manager pattern).

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239430

The "correct" way is: you don't. A controller should never directly call into another controller. You can redirect to a new route that maps to a different controller, but that's it. If you have some common logic that needs to be shared, then that should be factored out into a completely different class that both controllers can utilize.

Upvotes: 1

Related Questions