Puffix.IoC.Configuration 3.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Puffix.IoC.Configuration --version 3.0.0                
NuGet\Install-Package Puffix.IoC.Configuration -Version 3.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Puffix.IoC.Configuration" Version="3.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Puffix.IoC.Configuration --version 3.0.0                
#r "nuget: Puffix.IoC.Configuration, 3.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Puffix.IoC.Configuration as a Cake Addin
#addin nuget:?package=Puffix.IoC.Configuration&version=3.0.0

// Install Puffix.IoC.Configuration as a Cake Tool
#tool nuget:?package=Puffix.IoC.Configuration&version=3.0.0                

Puffix IoC Configuration

Extension for including Microsoft.Extensions.Configuration in the Puffix IoC library.

NuGet version (Puffix.IoC.Configuration) Build status

Minimal implementation

In the sample below, Autofac is used.

First, a base class is needed to reference the objects to map:

using Autofac;
using Microsoft.Extensions.Configuration;
using Puffix.IoC;
using Puffix.IoC.Configuration;

namespace YourAppName;

public class IoCContainer : IIoCContainerWithConfiguration
{
    private readonly IContainer? container;

    public IConfigurationRoot ConfigurationRoot { get; }

    public IoCContainer(ContainerBuilder containerBuilder, IConfigurationRoot configuration)
    {
        // Self-register the container.
        containerBuilder.Register(_ => this).As<IIoCContainerWithConfiguration>().SingleInstance();
        containerBuilder.Register(_ => this).As<IIoCContainer>().SingleInstance();

        container = containerBuilder.Build();
        ConfigurationRoot = configuration;
    }

    public static IIoCContainerWithConfiguration BuildContainer(IConfigurationRoot configuration)
    {
        ContainerBuilder containerBuilder = new ContainerBuilder();

        containerBuilder.RegisterAssemblyTypes
                        (
                            typeof(IoCContainer).Assembly // Current Assembly.
                        )
                        .AsSelf()
                        .AsImplementedInterfaces();

        containerBuilder.RegisterInstance(configuration).SingleInstance();

        return new IoCContainer(containerBuilder, configuration);
    }

    public ObjectT Resolve<ObjectT>(params IoCNamedParameter[] parameters)
        where ObjectT : class
    {
        if (container == null)
            throw new ArgumentNullException($"The class {GetType().Name} is not well initialized.");

        ObjectT resolvedObject;
        if (parameters != null)
            resolvedObject = container.Resolve<ObjectT>(ConvertIoCNamedParametersToAutfac(parameters));
        else
            resolvedObject = container.Resolve<ObjectT>();

        return resolvedObject;
    }

    public object Resolve(Type objectType, params IoCNamedParameter[] parameters)
    {
        if (container == null)
            throw new ArgumentNullException($"The class {GetType().Name} is not well initialized.");

        object resolvedObject;
        if (parameters != null)
            resolvedObject = container.Resolve(objectType, ConvertIoCNamedParametersToAutfac(parameters));
        else
            resolvedObject = container.Resolve(objectType);

        return resolvedObject;
    }

    private IEnumerable<NamedParameter> ConvertIoCNamedParametersToAutfac(IEnumerable<IoCNamedParameter> parameters)
    {
        foreach (var parameter in parameters)
        {
            if (parameter != null)
                yield return new NamedParameter(parameter.Name, parameter.Value);
        }
    }
}

To access Microsoft .NET configuration framework, you need to reference some Microsoft.Extensions.Configuration.* packages.

In the sample below, the following packages are referenced:

The container may be initialized like this:

IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
            .Build();

IIoCContainerWithConfiguration container = IoCContainer.BuildContainer();

And then you can resolve your objects in the code:

MyObject myObject = container.Resolve<MyObject>();

You can also access to the configuration like this:

string myStringParameter = container.ConfigurationRoot[nameof(myStringParameter)];
long myLongParameter = container.ConfigurationRoot.GetValue<int>(nameof(myLongParameter));

Use Polly to manage HttpClient

Polly is a library used to better manage the HttpClient instances.

The following packages are needed:

First, a base class is needed to reference the objects to map:

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Puffix.IoC;
using Puffix.IoC.Configuration;

namespace YourAppName;

public class IoCContainer : IIoCContainerWithConfiguration
{
    private readonly IContainer? container;

    public IConfigurationRoot ConfigurationRoot { get; }

    public IoCContainer(ContainerBuilder containerBuilder, IConfigurationRoot configuration)
    {
        // Self-register the container.
        containerBuilder.Register(_ => this).As<IIoCContainerWithConfiguration>().SingleInstance();
        containerBuilder.Register(_ => this).As<IIoCContainer>().SingleInstance();

        container = containerBuilder.Build();
        ConfigurationRoot = configuration;
    }

    public static IIoCContainerWithConfiguration BuildContainer(IConfigurationRoot configuration)
    {
        // Register HttpClientMessageFactory
        ServiceCollection services = new ServiceCollection();
        services.AddHttpClient();

        AutofacServiceProviderFactory providerFactory = new AutofacServiceProviderFactory();
        ContainerBuilder containerBuilder = providerFactory.CreateBuilder(services);

        containerBuilder.RegisterAssemblyTypes
                        (
                            typeof(IoCContainer).Assembly // Current Assembly.
                        )
                        .AsSelf()
                        .AsImplementedInterfaces();

        containerBuilder.RegisterInstance(configuration).SingleInstance();

        return new IoCContainer(containerBuilder, configuration);
    }

    public ObjectT Resolve<ObjectT>(params IoCNamedParameter[] parameters)
        where ObjectT : class
    {
        if (container == null)
            throw new ArgumentNullException($"The class {GetType().Name} is not well initialized.");

        ObjectT resolvedObject;
        if (parameters != null)
            resolvedObject = container.Resolve<ObjectT>(ConvertIoCNamedParametersToAutfac(parameters));
        else
            resolvedObject = container.Resolve<ObjectT>();

        return resolvedObject;
    }

    public object Resolve(Type objectType, params IoCNamedParameter[] parameters)
    {
        if (container == null)
            throw new ArgumentNullException($"The class {GetType().Name} is not well initialized.");

        object resolvedObject;
        if (parameters != null)
            resolvedObject = container.Resolve(objectType, ConvertIoCNamedParametersToAutfac(parameters));
        else
            resolvedObject = container.Resolve(objectType);

        return resolvedObject;
    }

    private IEnumerable<NamedParameter> ConvertIoCNamedParametersToAutfac(IEnumerable<IoCNamedParameter> parameters)
    {
        foreach (var parameter in parameters)
        {
            if (parameter != null)
                yield return new NamedParameter(parameter.Name, parameter.Value);
        }
    }
}

The container may be initialized like this:

IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
            .Build();

IIoCContainerWithConfiguration container = IoCContainer.BuildContainer();

And then you can resolve your objects in the code:

MyObject myObject = container.Resolve<MyObject>();

You can also access to the configuration like this (refer to the paragraph below for the required packages):

string myStringParameter = container.ConfigurationRoot[nameof(myStringParameter)];
long myLongParameter = container.ConfigurationRoot.GetValue<int>(nameof(myLongParameter));

Finally, here is a sample class where an HttpClient is needed:

using System.Text.Json;

namespace Puffix.Ovh.Api.Infra;

public MyClassWithHttpClient
{
    private readonly IHttpClientFactory httpClientFactory;

    public MyClassWithHttpClient(IHttpClientFactory httpClientFactory)
    {
        this.httpClientFactory = httpClientFactory;
    }

    public Task<string> CallHttpAsync(Uri targetUri)
    {
        using HttpClient httpClient = httpClientFactory.CreateClient();

        await AddHeadersAsync(httpClient, queryInformation);

        using HttpResponseMessage response = await httpClient.GetAsync(targetUri);

        if (!response.IsSuccessStatusCode)
        {
            string errorContent = await response.Content.ReadAsStringAsync();
            throw new Exception($"Error {response.StatusCode}: {response.ReasonPhrase} >> {errorContent}");
        }

        return  await response.Content.ReadAsStringAsync();
    }
}
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.3.0 180 11/12/2024
3.2.0 1,084 11/28/2023
3.1.0 1,037 11/16/2022
3.0.0 1,218 5/13/2022
2.0.0 842 11/11/2021
1.1.0 385 5/16/2021
1.0.0 411 1/8/2021

Extension for including Microsoft.Extensions.Configuration in the Puffix IoC library.