In C# 11 comes with .Net 7, Attribute is enhanced to use with generic type. This feature provides a convenient way for attributes to avoid System.Type constructor parameter (the old way).
Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime. Attributes are used to impose conditions or to increase the efficiency of a piece of code.
Being a programmer I love this. Here I will try to explain to you how to define Attributes with generic types. To understand the enhancement, let's see how we used to do the Attributes with type in C# 10 or before.
For example, we will create an Asp.Net core web API project template with the target framework net7.0 so the same project will be using the demonstration of old and new syntax.
Here I will be creating an Action Filter called LoggingFilter and will be logging some info before and after the execution of an action.
using Microsoft.AspNetCore.Mvc.Filters;
namespace CSharp11WebAPIDemo.Infrastructure
{
public class LoggingFilter : IAsyncActionFilter
{
public ILogger<LoggingFilter> _logger;
public LoggingFilter(ILogger<LoggingFilter> logger)
{
_logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
_logger.LogInformation("Action starts");
await next();
_logger.LogInformation("Action ends");
}
}
}
The above code is straightforward. So now we add this to the service collection.
builder.Services.AddSingleton<LoggingFilter>();
To use this action filter with an Action method we will use Microsoft.AspNetCore.Mvc.ServiceFilter attribute which is using the old syntax which takes System.Type as a parameter for the constructor and the definition of ServiceFilterAttribute.
Next, we will use the action filter with the Get action method of the WeatherForecastController generated from the template.
[HttpGet(Name = "GetWeatherForecast")]
[ServiceFilter(typeof(LoggingFilter))]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
Now you run the application and execute the GetWeatherForecast endpoint from the swagger app, you will see the information log in the output window as
CSharp11WebAPIDemo.Infrastructure.LoggingFilter: Information: Action starts
CSharp11WebAPIDemo.Infrastructure.LoggingFilter: Information: Action ends
Cool, Everything works great but How about Microsoft would have made the ServiceFilterAttribute generic and avoid the type parameter in the constructor? Well, we will do it and will write better code than Microsoft. :) Just kidding. Actually, this is the enhancement done in C#11, thanks to Microsoft for that.
To redefine the ServiceFilterAttribute using the Generic Attribute feature, let’s see the ServiceFilterAttribute code which is available under Microsoft.AspNetCore.Mvc namespace:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
[DebuggerDisplay("ServiceFilter: Type={ServiceType} Order={Order}")]
public class ServiceFilterAttribute : Attribute, IFilterFactory, IOrderedFilter
{
/// <summary>
/// Instantiates a new <see cref="ServiceFilterAttribute"/> instance.
/// </summary>
/// <param name="type">The <see cref="Type"/> of filter to find.</param>
public ServiceFilterAttribute(Type type)
{
ServiceType = type ?? throw new ArgumentNullException(nameof(type));
}
/// <inheritdoc />
public int Order { get; set; }
/// <summary>
/// Gets the <see cref="Type"/> of filter to find.
/// </summary>
public Type ServiceType { get; }
/// <inheritdoc />
public bool IsReusable { get; set; }
/// <inheritdoc />
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
var filter = (IFilterMetadata)serviceProvider.GetRequiredService(ServiceType);
if (filter is IFilterFactory filterFactory)
{
// Unwrap filter factories
filter = filterFactory.CreateInstance(serviceProvider);
}
return filter;
}
}
As per the above Microsoft code here, ServiceFilter takes Type as a parameter in the constructor which we pass as typeof(LoggingFilter) in the action method. So now we will recreate the ServiceFilterAttribute by defining a generic attribute and the syntax would be as:
public class MyServiceFilterAttribute<T> : Attribute
and the code as:
using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;
namespace CSharp11WebAPIDemo.Infrastructure
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class MyServiceFilterAttribute<T> : Attribute, IFilterFactory, IOrderedFilter
{
public int Order { get; set; }
public bool IsReusable { get; set; }
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
var filter = (IFilterMetadata)serviceProvider.GetRequiredService(typeof(T));
if (filter is IFilterFactory filterFactory)
{
filter = filterFactory.CreateInstance(serviceProvider);
}
return filter;
}
}
}
Wow, no more type parameters and a very convenient way of making the attribute class generic.
[HttpGet(Name = "GetWeatherForecast")]
[MyServiceFilter<LoggingFilter>]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
Again if you run the application, the logs will be displayed in the output window as with the earlier code.
CSharp11WebAPIDemo.Infrastructure.LoggingFilter: Information: Action starts
CSharp11WebAPIDemo.Infrastructure.LoggingFilter: Information: Action ends
No difference in functionality but a huge difference in terms of better code.
Here is the full code used for this example:
https://github.com/binodmahto/FunProjects/tree/main/CSharp11WebAPIDemo
To know more about C#11 new features please read through:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11
Hope you enjoyed the content, follow me for more like this, and please don’t forget to LIKE it. Happy programming.
No comments:
Post a Comment