Simply: I have noticed, that in ASP.NET Core MVC application, parameters to some functions use typically type Action<T> instead of type T. It is a bit strange, where can I found more info about that?

Example:

services.AddDbContext<FssDbContext>(options => 
  options.UseSqlServer(-something-));

More detailed: I am a newbie in ASP.NET Core, but not in .NET. I am working now on web ASP.NET Core MVC project and I have noticed that many function calls have as a parameter a System.Action<T> instead of T directly. I suppose that this is somehow closely related to DI and "not let the code-user creates an instance, but provide him some to adjust", but I'd like to know more info about that - especially if this is a common approach in .NET MVC/Core and where it should be used (and where is it not suggested), or even if it is some well-known defined concept I am missing.

However, I am not able to find anything about that, just the simple usages.

Is there any resource describing this behaviour, motivation, and suggestions?

Again, I am not interested "how can I create such behaviour", as I am not interested in "generic opinions", but if there is some official definition of this concept or globally well-known advice "where (/if) am I supposed to use it in .NET MVC/Core project" (e.g. from MS)?

1 Answers

0
Theraot On

I'm not familiar enough with ASP.NET to give you a full answer.

I can tell you that having Action<T> as parameter means that the library is ensuring you will pass something they can call. It is a callback.

They will be using it to give you a T object. Why would they do it (instead of, you know, returning T or using an out parameter)? Perhaps they need to do some clean up after you run your code, for example they will be catching exceptions, doing synchronization, disposing resources... something like that.

Another advantage of using a callback is that the library controls whatever or not you run the code. If they gives you a T object (and perhaps a bool to tell you to run your code), you might just ignore them.

It could also be that the code there is meant to run in a particular thread, it might even be that they will be running it in the future as the need arises, perhaps even multiple times. In fact, they can use it similar to an event, except you cannot subscribe and unsubscribe at arbitrary times.