Last active
May 13, 2020 00:23
-
-
Save Ablecken/6bba4e8251039a0e64bd to your computer and use it in GitHub Desktop.
ValueInjecter Create Type On Inject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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