Skip to content

Instantly share code, notes, and snippets.

@Ablecken
Last active May 13, 2020 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ablecken/6bba4e8251039a0e64bd to your computer and use it in GitHub Desktop.
Save Ablecken/6bba4e8251039a0e64bd to your computer and use it in GitHub Desktop.
ValueInjecter Create Type On Inject
using System;
using Omu.ValueInjecter.Injections;
// ReSharper disable once CheckNamespace
namespace Omu.ValueInjecter
{
#pragma warning disable 1591
public static class ValueInjecter
{
/// <summary>
/// Will create a new instance of TResult, then inject from object
/// </summary>
/// <typeparam name="TResult">Type of object to create</typeparam>
/// <param name="from">Object to inject from</param>
/// <param name="injection">injection to use</param>
/// <returns>A new object of type TResult</returns>
public static TResult InjectToType<TResult>(this object from, IValueInjection injection = null)
{
if (from == null) throw new ArgumentNullException(nameof(from));
return InjectToTypeFromMultiple<TResult>(injection, from);
}
/// <summary>
/// Will create a new instance of TResult, then inject from all objects
/// </summary>
/// <typeparam name="TResult">Type of object to create</typeparam>
/// <param name="objects">Objects to inject from</param>
/// <returns>A new object of type TResult</returns>
public static TResult InjectToTypeFromMultiple<TResult>(params object[] objects)
{
return InjectToTypeFromMultiple<TResult>(new LoopInjection(), objects);
}
/// <summary>
/// Will create a new instance of TResult, then inject from all objects
/// </summary>
/// <typeparam name="TResult">Type of object to create</typeparam>
/// <param name="injection">injection to use</param>
/// <param name="objects">Objects to inject from</param>
/// <returns>A new object of type TResult</returns>
public static TResult InjectToTypeFromMultiple<TResult>(IValueInjection injection = null, params object[] objects)
{
if (objects == null || objects.Length <= 0)
throw new ArgumentNullException(nameof(objects));
IValueInjection inject = injection ?? new LoopInjection();
TResult retVal = (TResult)Activator.CreateInstance(typeof(TResult));
foreach (var o in objects)
retVal.InjectFrom(injection, o);
return retVal;
}
}
#pragma warning restore 1591
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment