Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/tomlm/iciclecreek.json.net.dependencyinjection
Implements a IServiceProvider dependency injection factory for JSON.NET Deserialization.
https://github.com/tomlm/iciclecreek.json.net.dependencyinjection
Last synced: 5 days ago
JSON representation
Implements a IServiceProvider dependency injection factory for JSON.NET Deserialization.
- Host: GitHub
- URL: https://github.com/tomlm/iciclecreek.json.net.dependencyinjection
- Owner: tomlm
- License: mit
- Created: 2024-02-05T17:53:27.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2024-02-07T22:30:30.000Z (12 months ago)
- Last Synced: 2025-01-04T23:33:56.408Z (22 days ago)
- Language: C#
- Size: 14.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Iciclecreek.Json.Net.DependencyInjection
This library implements a JSON.NET converter which will use IServiceProvider to perform dependency injection as needed while deserializing.# Add NUGET package
To add to your project add
```dotnet add package Iciclecreek.Json.Net.DependencyInjection```# Description
There are 2 classes in this library
* **ServiceProviderConverter** - a universal converter which will use the IServiceProvider to instantiate objects that do not have a parameterless converter
* **ServiceProviderConvert** - A typed converter which will use IServiceProvider only for the given type T.# Usage
To use these converters you add them to the converters collection on **JsonSerializerSettings** object.Example for universal types needing dependency injection:
```C#
IServiceProvider serviceProvider = new ServiceCollection()
.AddSingleton((sp) => new JsonSerializerSettings()
{
Converters = new List()
{
new ServiceProviderConverter(sp)
}
})
// .., add other dependencies as needed ...
.BuildServiceProvider();
```Example for explicit resgistration just for types that need dependency injection:
```c#
IServiceProvider serviceProvider = new ServiceCollection()
.AddSingleton((sp) => new JsonSerializerSettings()
{
Converters = new List()
{
new ServiceProviderConverter(sp),
new ServiceProviderConverter(sp),
new ServiceProviderConverter(sp)
}
})
// .., add other dependencies as needed ...
.BuildServiceProvider();
```> NOTE: Registering for objects explicitely is slighty faster on first deserialization because the universal converter has to detect when an object can't be created.
Then simply use your json serializer settings when deserializing:
```c#
var result = JsonConvert.DeserializeObject(json, serviceProvider.GetRequiredService());
```