Exemple #1
0
        public static MyServiceCollection AddMyMediator(this MyServiceCollection services, MyServiceLifetime lifetime, params Type[] markers)
        {
            var handlersInfo = new Dictionary <Type, Type>();

            foreach (Type marker in markers)
            {
                var assembly = marker.Assembly;
                var requests = GetClassesImplementingInterface(assembly, typeof(IRequest <>));
                var handlers = GetClassesImplementingInterface(assembly, typeof(IRequestHandler <,>));

                foreach (Type request in requests)
                {
                    Type requestHandler = handlers.SingleOrDefault(h => request == h.GetInterfaces().First().GetGenericArguments().First());
                    handlersInfo.Add(request, requestHandler);
                }

                var serviceDescriptor = handlers.Select(x => new MyServiceDescriptor(x, x, lifetime));

                services.AddServiceDescriptor(serviceDescriptor);
            }

            services.RegisterSingleton <IMediator>(x => new MyMediator(x.GetService, handlersInfo));

            return(services);
        }
        static void Main(string[] args)
        {
            //var mySimpleContainer = new MySimpleContainer();
            //mySimpleContainer.Register<IRepository, Repository>(new Repository());

            //mySimpleContainer.Resolve<IRepository>();

            var myServiceCollection = new MyServiceCollection();

            myServiceCollection.RegisterTransient <IEmailSender, SmtpEmailSender>();
            myServiceCollection.RegisterSingleton <IRepository, Repository>();
            myServiceCollection.RegisterTransient <LoginController>();

            var myContainer = myServiceCollection.BuildContainer();
            var hash1       = myContainer.GetService <IRepository>().GetHashCode();
            var hash2       = myContainer.GetService <IRepository>().GetHashCode();

            var loginController = myContainer.GetService <LoginController>();
        }