Example #1
0
        private static object Create(Cat cat, Type type, Type[] genericArguments)
        {
            if (genericArguments.Length > 0)
            {
                type = type.MakeGenericType(genericArguments);
            }
            var constructors = type.GetConstructors();

            if (constructors.Length == 0)
            {
                throw new InvalidOperationException($"Cannot create the instance of {type} which does not have an public constructor.");
            }
            var constructor = constructors.FirstOrDefault(it => it.GetCustomAttributes(false).OfType <InjectionAttribute>().Any());

            constructor ??= constructors.First();
            var parameters = constructor.GetParameters();

            if (parameters.Length == 0)
            {
                return(Activator.CreateInstance(type));
            }
            var arguments = new object[parameters.Length];

            for (int index = 0; index < arguments.Length; index++)
            {
                arguments[index] = cat.GetService(parameters[index].ParameterType);
            }
            return(constructor.Invoke(arguments));
        }
Example #2
0
        static void Main(string[] args)
        {
            var cat = new Cat()
                      .Register <IFoo, Foo>(Lifetime.Transient)
                      .Register <IBar, Bar>(Lifetime.Transient)
                      .Register(typeof(IFoobar <,>), typeof(Foobar <,>), Lifetime.Transient);

            var foobar = (Foobar <IFoo, IBar>)cat.GetService <IFoobar <IFoo, IBar> >();

            Debug.Assert(foobar.Foo is Foo);
            Debug.Assert(foobar.Bar is Bar);
        }
Example #3
0
        private static void GetGenericService()
        {
            var cat = new Cat()
                      .Register <IFoo, Foo>(Lifetime.Transient)
                      .Register <IBar, Bar>(Lifetime.Transient)
                      .Register(typeof(IFoobar <,>), typeof(Foobar <,>), Lifetime.Transient);

            var foobar = (Foobar <IFoo, IBar>)cat.GetService <IFoobar <IFoo, IBar> >();

            Debug.Assert(foobar.Foo is Foo);
            Debug.Assert(foobar.Bar is Bar);
        }
Example #4
0
 public static IEnumerable <T> GetServices <T>(this Cat cat) => cat.GetService <IEnumerable <T> >();
Example #5
0
 public static T GetService <T>(this Cat cat) => (T)cat.GetService(typeof(T));