---
title: "ASP.NET Core Lazy Command Pattern - Muhammad Rehan Saeed"
description: "Move your ASP.NET Core MVC action method logic into lazily loaded commands using the command pattern, to reduce Controller complexity."
canonical_url: "https://rehansaeed.com/asp-net-core-lazy-command-pattern/"
last_updated: "2017-04-08T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: ".NET,.NET Core,ASP.NET Core,ASP.NET MVC,.NET Boxed,.NET Boxed API,C#,Command Pattern,Lazy"
  "og:description": "Move your ASP.NET Core MVC action method logic into lazily loaded commands using the command pattern, to reduce Controller complexity."
  "og:image": "https://rehansaeed.com/_og/s/o_fb6b417d1e8c027e.png"
  "og:image:alt": "ASP.NET Core Lazy Command Pattern - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "ASP.NET Core Lazy Command Pattern"
  "twitter:image": "https://rehansaeed.com/_og/s/o_fb6b417d1e8c027e.png"
  "twitter:image:alt": "ASP.NET Core Lazy Command Pattern - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [ASP.NET Core Lazy Command Pattern](https://rehansaeed.com/asp-net-core-lazy-command-pattern/)

Posted 8 April 2017 - **4 min read**

![ASP.NET Core-Lazy-Command-Pattern](https://rehansaeed.com/_ipx/f_webp&s_2560x1440/images/hero/ASP.NET-Core-Lazy-Command-Pattern-1366x768.png)

TLDR

Move your ASP.NET Core MVC action method logic into lazily loaded commands using the command pattern.

When writing your Controllers in ASP.NET Core, you can end up with a very long class if you're not careful. You may have written several action methods with a few lines of code in each, you may be injecting a few services into your controller and you may have commented your action methods to support Swagger. The point is it's very easy to do, here is an example:

```cs
[Route("[controller]")]
public class RocketController : Controller
{
    private readonly IPlanetRepository planetRepository;
    private readonly IRocketRepository rocketRepository;

    public RocketController(
        IPlanetRepository planetRepository,
        IRocketRepository rocketRepository)
    {
        this.planetRepository = planetRepository;
        this.rocketRepository = rocketRepository;
    }
    
    [HttpGet("{rocketId}")]
    public async Task<IActionResult> GetRocket(int rocketId)
    {
        var rocket = await this.rocketRepository.GetRocket(rocketId);
        if (rocket == null)
        {
            return this.NotFound();
       }
        return this.Ok(rocket);
    }
    
    [HttpGet("{rocketId}/launch/{planetId}")]
    public async Task<IActionResult> LaunchRocket(int rocketId, int planetId)
    {
        var rocket = await this.rocketRepository.GetRocket(rocketId);
        if (rocket == null)
        {
            return this.NotFound();
        }
        var planet = await this.planetRepository.GetPlanet(planetId);
        if (planet == null)
        {
            return this.NotFound();
        }
        this.rocketRepository.VisitPlanet(rocket, planet);
        return this.Ok(rocket);
    }
}
```

# The Command Pattern

This is where the command pattern can come in handy. The command pattern moves logic from each action method and injected dependencies into their own class like so:

```cs
[Route("[controller]")]
public class RocketController : Controller
{
    private readonly Lazy<IGetRocketCommand> getRocketCommand;
    private readonly Lazy<ILaunchRocketCommand> launchRocketCommand;

    public RocketController(
        Lazy<IGetRocketCommand> getRocketCommand,
        Lazy<ILaunchRocketCommand> launchRocketCommand)
    {
        this.getRocketCommand = getRocketCommand;
        this.launchRocketCommand = launchRocketCommand;
    }

    [HttpGet("{rocketId}")]
    public Task<IActionResult> GetRocket(int rocketId) =>
        this.getRocketCommand.Value.ExecuteAsync(rocketId);

    [HttpGet("{rocketId}/launch/{planetId}")]
    public Task<IActionResult> LaunchRocket(int rocketId, int planetId) =>
        this.launchRocketCommand.Value.ExecuteAsync(rocketId, planetId);
}

public interface IGetRocketCommand : IAsyncCommand<int>
{
}

public class GetRocketCommand : IGetRocketCommand
{
    private readonly IRocketRepository rocketRepository;

    public GetRocketCommand(IRocketRepository rocketRepository) =>
        this.rocketRepository = rocketRepository;

    public async Task<IActionResult> ExecuteAsync(int rocketId)
    {
        var rocket = await this.rocketRepository.GetRocket(rocketId);
        if (rocket == null)
        {
            return new NotFoundResult();
        }
        return new OkObjectResult(rocket);
    }
}
```

All the logic and dependencies in the controllers gets moved to the command which now has a single responsibility. The controller now has a different set of dependencies, it now lazily injects one command per action method.

You may have noticed the `IAsyncCommand` interface. I keep four of these handy to inherit from. They all outline an `ExecuteAsync` method to execute the command and return an `IActionResult` but they have a differing number of parameters. I personally feel if you are needing more than three parameters you should be using a class to represent your parameters, so I've put the limit on three parameters.

```cs
public interface IAsyncCommand
{
    Task<IActionResult> ExecuteAsync();
}
public interface IAsyncCommand<T>
{
    Task<IActionResult> ExecuteAsync(T parameter);
}
public interface IAsyncCommand<T1, T2>
{
    Task<IActionResult> ExecuteAsync(T1 parameter1, T2 parameter2);
}
public interface IAsyncCommand<T1, T2, T3>
{
    Task<IActionResult> ExecuteAsync(T1 parameter1, T2 parameter2, T3 parameter3);
}
```

# Why so Lazy?

Why do we use `Lazy<T>`? Well the answer is that if we have multiple action methods on our controller, we don't want to instantiate the dependencies for every action method if we are only planning on using one action method. Registering our Lazy commands requires a bit of extra work in out `Startup.cs`. We can register lazy dependencies like so:

```cs
public void ConfigureServices(IServiceCollection services)
{
    // ...Omitted
    services
        .AddScoped<IGetRocketCommand, GetRocketCommand>()
        .AddScoped(x => new Lazy<IGetRocketCommand>(
            () => x.GetRequiredService<IGetRocketCommand>()));
}
```

# HttpContext and ActionContext

Now you might be thinking, how do I access the `HttpContext` or `ActionContext` if I want to set a HTTP header for example? Well, you can use the `IHttpContextAccessor` or `IActionContextAccessor` interfaces for this purpose. You can register them in your `Startup` class like so:

```cs
public void ConfigureServices(IServiceCollection services)
{
    // ...Omitted
    services
        .AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
        .AddSingleton<IActionContextAccessor, ActionContextAccessor>();
}
```

Notice that they can be registered as singletons. You can then use them to get hold of the `HttpContext` or `ActionContext` objects for the current HTTP request. Here is a really simple example.

```cs
public class SetHttpHeaderCommand : ISetHttpHeaderCommand
{
    private readonly IHttpContextAccessor httpContextAccessor;

    public GetRocketCommand(IHttpContextAccessor httpContextAccessor) =>
        this.httpContextAccessor = httpContextAccessor;

    public async Task<IActionResult> ExecuteAsync()
    {
        this.httpContextAccessor.HttpContext.Response.Headers.Add("X-Rocket", "Saturn V");
        return new OkResult();
    }
}
```

# Unit Testing

Another upside to the command pattern is that testing each command becomes super simple. You don't need to setup a controller with lots of dependencies that you don't care about. You only need to write test code for that single feature.

# Conclusions

For a full working example, take a look at the [.NET Boxed API](https://github.com/Dotnet-Boxed/Templates/blob/main/Docs/API.md) project template which makes full use of the Lazy Command Pattern.

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## Comment

[Leave and View Directly on GitHub.com](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57)

18 Comments

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236318)

[![Mike-EEE](https://camo.githubusercontent.com/073a637e433812126b5ee5a88d9b27ce08c510387a14507f2429287cfae86b16/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63386561643331323263363239313934636233306437623331636461363962653f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/073a637e433812126b5ee5a88d9b27ce08c510387a14507f2429287cfae86b16/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63386561643331323263363239313934636233306437623331636461363962653f733d393626643d6d6d26723d67) **[Mike-EEE](http://blog.developers.win/)** commented on **2017-04-08 12:45:46**

Command pattern is indeed awesome! Thank you for promoting it. As you may know, it was a staple in WPF development.

Quick commentary, however. ;) What used to be a simple:

```
void ICommand.Execute(T parameter)
```

... in WPF is now:

```
Task IAsyncCommand.ExecuteAsync(T parameter)
```

... in .NET Core. So, 38 characters "old" way vs. 62 characters "new" way. So much for progress. ;) As you are using an expression body for the constructor I am sure you can appreciate the sentiment that less code is better.

https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/9126493-improve-asynchronous-programming-model

Additionally, this design muddies the water with command and query separation, essentially forcing you to enable every "query" method (anything that returns a result) into a command method, which implicitly changes state and has side effects (which query methods are not supposed to have).

Food for thought. :)

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236379)

[![Mike-EEE](https://camo.githubusercontent.com/073a637e433812126b5ee5a88d9b27ce08c510387a14507f2429287cfae86b16/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63386561643331323263363239313934636233306437623331636461363962653f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/073a637e433812126b5ee5a88d9b27ce08c510387a14507f2429287cfae86b16/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63386561643331323263363239313934636233306437623331636461363962653f733d393626643d6d6d26723d67) **[Mike-EEE](http://blog.developers.win/)** commented on **2017-04-08 12:49:17**

> Command pattern is indeed awesome! Thank you for promoting it. As you may know, it was a staple in WPF development.
>
> Quick commentary, however. ;) What used to be a simple:
>
> ```
> void ICommand.Execute(T parameter)
> ```
>
> ... in WPF is now:
>
> ```
> Task IAsyncCommand.ExecuteAsync(T parameter)
> ```
>
> ... in .NET Core. So, 38 characters "old" way vs. 62 characters "new" way. So much for progress. ;) As you are using an expression body for the constructor I am sure you can appreciate the sentiment that less code is better.
>
> https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/9126493-improve-asynchronous-programming-model
>
> Additionally, this design muddies the water with command and query separation, essentially forcing you to enable every "query" method (anything that returns a result) into a command method, which implicitly changes state and has side effects (which query methods are not supposed to have).
>
> Food for thought. :)

Boo, the blog formatted out the brackets. Let's see if JSON-based formatting works (sigh):

```
void ICommand{T}.Execute(T parameter)

Task{IActionResult} IAsyncCommand{T}.ExecuteAsync(T parameter)
```

It's actually 37 "old" vs 62 "new."

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236448)

[![Manuel Grundner](https://camo.githubusercontent.com/6be4cff7e60019bb481bce35c8ed7283a99c0acce5921f7326b1760cd5c502f0/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31383366663661333737333663333132366362363130633262386661653966353f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/6be4cff7e60019bb481bce35c8ed7283a99c0acce5921f7326b1760cd5c502f0/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31383366663661333737333663333132366362363130633262386661653966353f733d393626643d6d6d26723d67) **[Manuel Grundner](http://blog.delegate.at/)** commented on **2017-04-08 14:20:58**

I totally understand the SRP and the IOC Concept behind this, but whats then the purpose of the Controller? Besides declaring The Routes? I mean in a more reallife Example?

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236510)

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2017-04-08 16:40:34**

> I totally understand the SRP and the IOC Concept behind this, but whats then the purpose of the Controller? Besides declaring The Routes? I mean in a more reallife Example?

I think of a controller as a kind of specialized interface for HTTP or maybe a better way to describe it would be a contract. It has all your routes, caching and authorization attributes etc. It defines the public contract for how you want to do HTTP.

In an imaginary world where each action method was turned into an action command class, it'd be quite difficult to get a quick overview of all of your HTTP endpoints, although such an architecture might be cool.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236576)

[![Adie](https://camo.githubusercontent.com/d9eeee4c752f49ad04d87c80ac4362d5c5426125f8cf3c37b10ef969efb01470/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f37653536356236663434313936396664616434646564303332316665336637353f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/d9eeee4c752f49ad04d87c80ac4362d5c5426125f8cf3c37b10ef969efb01470/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f37653536356236663434313936396664616434646564303332316665336637353f733d393626643d6d6d26723d67) **Adie** commented on **2017-04-09 15:50:02**

Nice idea, better sample with asp identity would be nice

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236633)

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2017-04-09 16:03:11**

> Nice idea, better sample with asp identity would be nice

Agreed. ASP.NET Identity is a mess and a prime example of code that could use the command pattern. Not enough time in my day to show that though, so that's an exercise for the reader.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236703)

[![Paul](https://camo.githubusercontent.com/216c09e3d7f5b502fc6a61fff1d4f717bb4cb8dc3eac735fccfc9f8a149b6ae0/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63386635343033656537326664393763623836363432613333363337616463333f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/216c09e3d7f5b502fc6a61fff1d4f717bb4cb8dc3eac735fccfc9f8a149b6ae0/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f63386635343033656537326664393763623836363432613333363337616463333f733d393626643d6d6d26723d67) **[Paul](http://paulwheeler.com/)** commented on **2017-04-11 14:38:04**

I use Jimmy Bogard's [MediatR](https://github.com/jbogard/MediatR) project to accomplish a similar purpose where controllers simply execute commands and queries. I love that pattern!

```
public class Ping : IRequest
{
    public string Name { get; set; }

    public class Pong 
    {
        public string Message { get; set; }
    }

    internal class Handler : IRequestHandler 
    {     
        public Pong Handle(Ping request)
        {
            return new Pong { 
                Message = "Ping: " + request.Name
            };
        }
    }
}
```

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236765)

[![Theo Albers](https://camo.githubusercontent.com/8d9a321c57824c2adb0d67cb38265ca241897d2845248019d34511040a96cbe5/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31656233316537616161353833663361323036623839373365653335326131353f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8d9a321c57824c2adb0d67cb38265ca241897d2845248019d34511040a96cbe5/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31656233316537616161353833663361323036623839373365653335326131353f733d393626643d6d6d26723d67) **Theo Albers** commented on **2017-04-13 09:14:44**

I have used this pattern as well to keep the API controller lean. I decided to move the "protocol" out of the command and into the controller action. So the command returns an object and the controller action returns the wire result `NotFoundResult`/`OkObjectResult`.

The question that keeps spinning in my head: why not create `ApiControllers` with a single method? So instead of `RocketController` have `RocketGetController`, `RocketLaunchController`. That way the controller turns into a command/action.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236832)

[![Juan Perez](https://camo.githubusercontent.com/24f3f48bb34e5125e08510d76c593f04e7222ab3e88517bed2a9cd52ff5dde70/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f66626238633139656161623662623734356461663263333032616537663337393f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/24f3f48bb34e5125e08510d76c593f04e7222ab3e88517bed2a9cd52ff5dde70/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f66626238633139656161623662623734356461663263333032616537663337393f733d393626643d6d6d26723d67) **Juan Perez** commented on **2017-04-18 17:31:38**

> I think of a controller as a kind of specialized interface for HTTP or maybe a better way to describe it would be a contract. It has all your routes, caching and authorization attributes etc. It defines the public contract for how you want to do HTTP.
>
> In an imaginary world where each action method was turned into an action command class, it'd be quite difficult to get a quick overview of all of your HTTP endpoints, although such an architecture might be cool.

I do not totally agree. If you organize the commands in folder or namespaces and use names related to HTTP methods, it could be better and simpler. It is almost like a class for each action.

We could create controllers that implement command interface and we could avoid all these ugly Lazy fields.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236897)

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2017-04-21 15:32:39**

> I have used this pattern as well to keep the API controller lean. I decided to move the "protocol" out of the command and into the controller action. So the command returns an object and the controller action returns the wire result `NotFoundResult`/`OkObjectResult`.
>
> The question that keeps spinning in my head: why not create `ApiControllers` with a single method? So instead of `RocketController` have `RocketGetController`, `RocketLaunchController`. That way the controller turns into a command/action.

Controllers with a single action method are interesting and certainly a possible direction. I personally feel that an action method is doing two things:

1. Defines an interface for a request.
2. Builds and returns a response.  
    These two things go against the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle). When you are working on building a reponse, you don't care about the request interface (routes, auth etc.), thats all noise. A controller per action method would also make it more difficult to see all your related routes in one place. Using the command pattern, the controller just becomes a specialized interface for HTTP.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627236974)

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2017-04-21 15:33:18**

> I do not totally agree. If you organize the commands in folder or namespaces and use names related to HTTP methods, it could be better and simpler. It is almost like a class for each action.
>
> We could create controllers that implement command interface and we could avoid all these ugly Lazy fields.

See my answer to Theo Albers.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627237036)

[![paul](https://camo.githubusercontent.com/bd8ecfbb9f1a881c755b1c3711ee2ac510efb53b03a5659558654d4925b1de71/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f65386263376439393264396432313435353262643562333230623639616533613f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/bd8ecfbb9f1a881c755b1c3711ee2ac510efb53b03a5659558654d4925b1de71/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f65386263376439393264396432313435353262643562333230623639616533613f733d393626643d6d6d26723d67) **paul** commented on **2017-04-29 23:44:52**

> Controllers with a single action method are interesting and certainly a possible direction. I personally feel that an action method is doing two things:
>
> 1. Defines an interface for a request.
> 2. Builds and returns a response.  
>     These two things go against the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle). When you are working on building a reponse, you don't care about the request interface (routes, auth etc.), thats all noise. A controller per action method would also make it more difficult to see all your related routes in one place. Using the command pattern, the controller just becomes a specialized interface for HTTP.

I agree with Theo that I cannot see how this approach offers any benefit over 'one action controllers' and in fact it just adds complexity. You mentioned that the controller defies the interface for the request but this is not strictly true. The route is only part of the interface. The request and response types are also a significant part of the contract and these are defined in the command. So now we have the command being responsible for some of 1) and all of 2). Just my two cents.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627237106)

[![XperiAndri](https://camo.githubusercontent.com/3b30bf0ace08d58974339751ba76131cc9d88e19a29916cf98e5a351fb945bbc/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f35336437386630633038366362323333373538343933303862396236626434333f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/3b30bf0ace08d58974339751ba76131cc9d88e19a29916cf98e5a351fb945bbc/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f35336437386630633038366362323333373538343933303862396236626434333f733d393626643d6d6d26723d67) **XperiAndri** commented on **2017-07-15 15:28:28**

Looks interesting however very verbose and overcomplicated.  
 Solutions with MediatR look much more concise and elegant.

And in my opinion your current implementation look like moving controller specific stuff to business layer.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627237164)

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2017-07-23 12:37:56**

> Looks interesting however very verbose and overcomplicated.  
>  Solutions with MediatR look much more concise and elegant.
>
> And in my opinion your current implementation look like moving controller specific stuff to business layer.

MediatR is interesting but it's another dependency, and much slower than this implementation because it uses `Activator.CreateInstance()`. This implementation is much simpler (a couple of interfaces used by the DI container, has zero dependencies and is as fast as it gets.

I debated with myself whether the controller should return a business object or an `IActionResult`. I actually started with the former but settled on the latter. It makes things much simpler, it's all C# POCO's which makes unit testing a breeze.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627237208)

[![Manish](https://camo.githubusercontent.com/8b934faeefede6c8e8e1f225ba3467ab3af282fcb32d2c4f1a7e440c2c149934/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f39613866333738323436383065333238393831633466306436663733633231613f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8b934faeefede6c8e8e1f225ba3467ab3af282fcb32d2c4f1a7e440c2c149934/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f39613866333738323436383065333238393831633466306436663733633231613f733d393626643d6d6d26723d67) **Manish** commented on **2017-08-22 03:51:20**

> I have used this pattern as well to keep the API controller lean. I decided to move the "protocol" out of the command and into the controller action. So the command returns an object and the controller action returns the wire result `NotFoundResult`/`OkObjectResult`.
>
> The question that keeps spinning in my head: why not create `ApiControllers` with a single method? So instead of `RocketController` have `RocketGetController`, `RocketLaunchController`. That way the controller turns into a command/action.

Hello,  
 How did you do it? Can you please post sample code?

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [12 May 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-627237269)

[![Aluan Haddad](https://camo.githubusercontent.com/3c5615198835748b0a6883906ec865eb5fc5c540e256bc7f1bdacb271ede8e78/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f35383062333162306265373137336262633437376361316436393637643837633f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/3c5615198835748b0a6883906ec865eb5fc5c540e256bc7f1bdacb271ede8e78/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f35383062333162306265373137336262633437376361316436393637643837633f733d393626643d6d6d26723d67) **[Aluan Haddad](http://lasi-project.org/)** commented on **2018-01-20 11:13:20**

While abstracting away common patterns is of course good, this overlooks the basic facilities the language already provides to accomplish this.

The `IAsyncCommand` interfaces you have defined introduce unnecessary complexity and represent a barrier to simple composition. In particular, the whole pattern reeks of Java and the complexity and ugliness inherent in its abhorrent SAM types.

This is C#, we don't need nonsensical, SAM types, we have delegates.

[![TarasKuz](https://avatars.githubusercontent.com/u/32145357?v=4)](https://github.com/TarasKuz)

[TarasKuz](https://github.com/TarasKuz) [25 September 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-699198928)

Instead of your lazy stuff use FromServicesAttribute for each action/command

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

[RehanSaeed](https://github.com/RehanSaeed) [26 September 2020](https://github.com/RehanSaeed/rehansaeed.github.io/issues/57#issuecomment-699496418)

> Instead of your lazy stuff use FromServicesAttribute for each action/command

[@TarasKuz](https://github.com/TarasKuz) Agreed, soon after I wrote this, I switched to using `[FromServices]`.

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/#webpage","@type":"WebPage","dateModified":"2017-04-08T00:00:00+00:00","datePublished":"2017-04-08T00:00:00+00:00","description":"Move your ASP.NET Core MVC action method logic into lazily loaded commands using the command pattern, to reduce Controller complexity.","name":"ASP.NET Core Lazy Command Pattern","url":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/","breadcrumb":{"@id":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/asp-net-core-lazy-command-pattern/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/#article","@type":"Article","dateModified":"2017-04-08T00:00:00+00:00","datePublished":"2017-04-08T00:00:00+00:00","description":"Move your ASP.NET Core MVC action method logic into lazily loaded commands using the command pattern, to reduce Controller complexity.","headline":"ASP.NET Core Lazy Command Pattern","inLanguage":"en-GB","url":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/ASP.NET-Core-Lazy-Command-Pattern-1366x768.png","caption":"ASP.NET Core-Lazy-Command-Pattern","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/#webpage"},"keywords":[".NET",".NET Core","ASP.NET Core","ASP.NET MVC",".NET Boxed",".NET Boxed API","C#","Command Pattern","Lazy"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"ASP.NET Core Lazy Command Pattern","item":"https://rehansaeed.com/asp-net-core-lazy-command-pattern/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
