The DataShaper<T>
service allows you to shape objects and collections dynamically by selecting specific fields at runtime. This is useful for implementing dynamic field selection in REST APIs (e.g., for performance or customization).
- Dynamically select properties of an object or collection.
- Useful for building clean, efficient API responses.
- Integrates easily with ASP.NET Core's Dependency Injection (DI) system.
Just add the IDataShaper<T>
and DataShaper<T>
classes to your project. Then register the service in the DI container.
Add this to your Startup.cs
(ASP.NET Core 5) or Program.cs
(ASP.NET Core 6+):
builder.Services.AddScoped(typeof(IDataShaper<>), typeof(DataShaper<>));
This allows the service to be injected anywhere using generics.
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; } = default!;
public string LastName { get; set; } = default!;
public int Age { get; set; }
}
public class PeopleService
{
private readonly IDataShaper<Person> _dataShaper;
public PeopleService(IDataShaper<Person> dataShaper)
{
_dataShaper = dataShaper;
}
public IEnumerable<Dictionary<string, object?>> GetPeopleShaped(IEnumerable<Person> people, string? fields)
{
return _dataShaper.ShapeData(people, fields);
}
}
var people = new List<Person>
{
new Person { Id = 1, FirstName = "Alice", LastName = "Smith", Age = 30 },
new Person { Id = 2, FirstName = "Bob", LastName = "Johnson", Age = 25 }
};
var shaped = _dataShaper.ShapeData(people, "Id,FirstName");
[
{ "Id": 1, "FirstName": "Alice" },
{ "Id": 2, "FirstName": "Bob" }
]
If fields
is null
or empty, all properties will be included.
- Property names in the
fields
string are case-insensitive. - If a field in the string doesn’t exist on the model, it will be ignored.
- Works best when combined with API query parameters like
?fields=Id,Name
.