Esempio n. 1
0
 public void RegisterServices(IServiceCollection services, IRegisterContext context)
 {
     services.ConfigureDynamicProxy(config =>
     {
         config.ThrowAspectException = false;
     });
 }
Esempio n. 2
0
        public void RegisterServices(IServiceCollection services, IRegisterContext context)
        {
            var swaggerOptions = context?.Configuration.GetConfigOrNew <SwaggerOptions>();

            if (swaggerOptions.Mode == Mode.None)
            {
                return;
            }
            services.AddSwaggerGen(c =>
            {
                var api          = swaggerOptions.Api ?? new ApiInfo();
                var documentName = swaggerOptions.GetDocumentNameOrEntryAssemblyName();
                c.SwaggerDoc(documentName,
                             new OpenApiInfo
                {
                    Title       = api.GetTitleOrAssemblyTitle(),
                    Version     = api.GetVersionOrAssemblyVersion(),
                    Description = api.GetDescriptionOrAssemblyDescription()
                });
                if (api.IncludeXmlComments)
                {
                    var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                    foreach (var file in Directory.GetFiles(basePath, api.XmlCommentsFiles))
                    {
                        c.IncludeXmlComments(file);
                    }
                    ;
                }
            });
        }
Esempio n. 3
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            _ = declareType ?? throw new ArgumentNullException(nameof(declareType));
            _ = context ?? throw new ArgumentNullException(nameof(context));


            string connectionStringKey = string.IsNullOrEmpty(this.ConnectionStringKey)
                ? declareType.Name
                : this.ConnectionStringKey;
            string connectionString = context.Configuration.GetConnectionString(connectionStringKey);

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ApplicationException($"Can not find connection string by key \"{connectionStringKey}\".");
            }
            var injectType = declareType;

            while (injectType != typeof(DbContext))
            {
                var method = typeof(EFContextAttribute)
                             .GetMethod(nameof(AddDbContext2), BindingFlags.Instance | BindingFlags.NonPublic)
                             ?.MakeGenericMethod(injectType, declareType);
                method.Invoke(this, new object[] { services, connectionString, this.InterceptorTypes });
                injectType = injectType.BaseType;
            }
            if (RegisterEntityStore)
            {
                AddEntityStoresInternal(services, declareType);
            }
        }
 public virtual void RegisterServices(IServiceCollection services, IRegisterContext context)
 {
     foreach (var type in AppDomain.CurrentDomain.FindInstanceTypesByAttribute <KnifeAttribute>())
     {
         if (context.HasFiltered(type))
         {
             continue;
         }
         foreach (var injectAttribute in type.GetCustomAttributes(typeof(KnifeAttribute), true).Cast <KnifeAttribute>())
         {
             if (injectAttribute.ValidateFromType != null)
             {
                 if (injectAttribute.ValidateFromType.IsGenericTypeDefinition)
                 {
                     if (!IsAssignableFromGenericType(type, injectAttribute.ValidateFromType))
                     {
                         throw new InvalidOperationException($"The type '{type.FullName}' must be a child class from '{injectAttribute.ValidateFromType.FullName}'.");
                     }
                 }
                 else
                 {
                     if (!injectAttribute.ValidateFromType.IsAssignableFrom(type))
                     {
                         throw new InvalidOperationException($"The type '{type.FullName}' must be a child class from '{injectAttribute.ValidateFromType.FullName}'.");
                     }
                 }
             }
             injectAttribute.RegisterService(services, context, type);
         }
     }
 }
Esempio n. 5
0
        private void RegisterController(IServiceCollection services, IRegisterContext context)
        {
            var         options    = context.Configuration.GetConfigOrNew <KnifeWebOptions>();
            IMvcBuilder mvcBuilder = services.AddMvc((mvc) =>
            {
                if (options.WrapCodeException)
                {
                    mvc.Filters.Add(typeof(WrapCodeMessageAttribute));
                }
                // if the Accept type not provide, return 406 code
                mvc.ReturnHttpNotAcceptable = true;
            }).AddXmlDataContractSerializerFormatters();

            var controllerAssemblies = AppDomain.CurrentDomain.FindInstanceTypesByAttribute <ControllerAttribute>()
                                       .Select(p => p.Assembly)
                                       .Distinct();

            foreach (var mvcPart in controllerAssemblies)
            {
                mvcBuilder.AddApplicationPart(mvcPart);
            }
            mvcBuilder.ConfigureApplicationPartManager((manager =>
            {
                // generic controller
                manager.FeatureProviders.Add(new GenericControllerFeatureProvider(context));
            }));
        }
        public void RegisterAssembly(IRegisterContext context)
        {
            //1:ITransient
            context.IocManager.IocContainer.Register(
                Classes.FromAssembly(context.Assembly)
                .IncludeNonPublicTypes()
                .BasedOn <ITransientDependency>()
                .If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
                .WithService.Self()
                .WithService.DefaultInterfaces()
                .LifestyleTransient());

            //2:ISingleton
            context.IocManager.IocContainer.Register(
                Classes.FromAssembly(context.Assembly)
                .IncludeNonPublicTypes()
                .BasedOn <ISingletonDependency>()
                .If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
                .WithService.Self()
                .WithService.DefaultInterfaces()
                .LifestyleSingleton());

            //3:注入拦截器
            context.IocManager.IocContainer.Register(
                Classes.FromAssembly(context.Assembly)
                .IncludeNonPublicTypes()
                .BasedOn <IInterceptor>()
                .If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
                .WithService.Self()
                .LifestyleTransient()
                );
        }
Esempio n. 7
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            _ = declareType ?? throw new ArgumentNullException(nameof(declareType));
            var optionsType = FindOptionsType(declareType);

            services.AddSingleton(typeof(IPostConfigureOptions <>).MakeGenericType(optionsType), declareType);
        }
Esempio n. 8
0
 public void RegisterServices(IServiceCollection services, IRegisterContext context)
 {
     if (context.HasFiltered(typeof(IDictionary <,>)))
     {
         return;
     }
     services.AddTransient(typeof(IDictionary <,>), typeof(KnifeInjectionDictionary <,>));
 }
 public void RegisterAssembly(IRegisterContext context)
 {
     context.IocManager.IocContainer.Register(
         Classes.FromAssembly(context.Assembly)
         .BasedOn <Controller>()
         //非泛型
         .If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
         .LifestyleTransient());
 }
Esempio n. 10
0
 public void Register(IRegisterContext context)
 {
     Initialise();
     if (!modules.Any())
     {
         return;
     }
     var result = modules[0].Register(context);
 }
Esempio n. 11
0
        public override bool Register(IRegisterContext context)
        {
            context.builder.RegisterModule(new AutofacDataModule());
            context.builder.RegisterModule(new AutofacEntityFrameworkModule());

            base.Next(context);

            logger.Info("EF Module initialed...");
            return(true);
        }
        public override bool Register(IRegisterContext context)
        {
            context.builder.RegisterModule(new DataAutofacModule(dbConnectionProvider));
            context.builder.RegisterModule(new EntityFrameworkAutofacModule(dbConnectionProvider));

            base.Next(context);

            logger.Info("EF Module initialed...");
            return(true);
        }
Esempio n. 13
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            services.AddHealthChecks();
            string healthCheckName = this.Name == null ? declareType?.FullName : this.Name;

            services.Configure <HealthCheckServiceOptions>(option =>
            {
                this.RemoveTheSameName(option.Registrations, healthCheckName);
                this.AddHealthCheck(option.Registrations, declareType, healthCheckName);
            });
        }
Esempio n. 14
0
 public static bool HasFiltered(this IRegisterContext context, Type type)
 {
     if (context == null)
     {
         throw new ArgumentNullException(nameof(context));
     }
     if (context.TypeFilter == null)
     {
         return(false);
     }
     return(context.TypeFilter(type));
 }
Esempio n. 15
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            _ = context ?? throw new ArgumentNullException(nameof(declareType));
            _ = declareType ?? throw new ArgumentNullException(nameof(declareType));
            var injectType = this.InjectType ?? DeduceInjectType(declareType);

            services.Add(new ServiceDescriptor(injectType, declareType, this.Lifetime));
            if (injectType != declareType)
            {
                services.Add(new ServiceDescriptor(declareType, declareType, this.Lifetime));
            }
        }
Esempio n. 16
0
 public void RegisterServices(IServiceCollection services, IRegisterContext context)
 {
     services.AddSingleton <IConnectionMultiplexer>((sp) =>
     {
         var options = sp.GetService <RedisOptions>();
         return(CreateConnection(options));
     });
     services.AddSingleton <IDatabase>(sp =>
     {
         var connection = sp.GetRequiredService <IConnectionMultiplexer>();
         return(connection.GetDatabase());
     });
 }
Esempio n. 17
0
        public void RegisterServices(IServiceCollection services, IRegisterContext context)
        {
            var options = context.Configuration.GetConfigOrNew <GrpcServiceOptions>();

            services.AddGrpc(op =>
            {
                CopyProperties(options, op);
            });
            if (options.EnableReflection)
            {
                services.AddGrpcReflection();
            }
        }
Esempio n. 18
0
 public void RegisterServices(IServiceCollection services, IRegisterContext context)
 {
     services.AddSingleton <ElasticClient>((sp) =>
     {
         var options  = sp.GetRequiredService <ElasticOptions>();
         var allUrls  = (options.Urls ?? Enumerable.Empty <string>()).Select(p => new Uri(p));
         var pool     = new StaticConnectionPool(allUrls);
         var settings = new ConnectionSettings(pool)
                        .DefaultIndex(options.DefaultIndex);
         return(new ElasticClient(settings));
     });
     services.AddSingleton <IElasticClient>(sp => sp.GetRequiredService <ElasticClient>());
 }
Esempio n. 19
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            _ = declareType ?? throw new ArgumentNullException(nameof(declareType));

            var injectType = this.InjectType ?? DeduceInjectType(declareType);

            if (injectType != null && injectType != declareType)
            {
                services.AddTransient(injectType, (sp) => sp.GetService(declareType));
            }
            var method = typeof(RestClientAttribute).GetMethod(nameof(RegisterHttpClientAndRestInfo), BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(declareType);

            method.Invoke(this, new object[] { services, this.MessageHandlerTypes });
        }
Esempio n. 20
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            //services.AddGrpcClient<>()
            var method = typeof(GrpcClientAttribute).GetMethod(nameof(RegisterGrpcClient), BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(declareType);

            method.Invoke(this, new object[] { services, context?.Configuration });

            var injectType = this.InjectType ?? (AutoDeduceInterfaceType ? DeduceInjectInterfaceType(declareType) : null);

            if (injectType != null && injectType != declareType)
            {
                // every time from service provider get the grpc client
                services.AddTransient(injectType, sp => sp.GetService(declareType));
            }
        }
Esempio n. 21
0
        public async Task <Result> Register(IRegisterContext model)
        {
            var user = new IdentityUser {
                UserName = model.Username
            };
            var result = await this.userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(result.ToApplicationResult());
            }

            await this.signInManager.SignInAsync(user, isPersistent : false);

            return(Result.Success);
        }
Esempio n. 22
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            _ = declareType ?? throw new ArgumentNullException(nameof(declareType));
            _ = context ?? throw new ArgumentNullException(nameof(context));

            var method = typeof(EFCoreContextAttribute)
                         .GetMethod(nameof(AddDbContext2), BindingFlags.Instance | BindingFlags.NonPublic)
                         ?.MakeGenericMethod(declareType);

            method.Invoke(this, new object[] { services });

            if (RegisterEntityStore)
            {
                AddEntityStoresInternal(services, declareType);
            }
        }
Esempio n. 23
0
        public void RegisterServices(IServiceCollection services, IRegisterContext context)
        {
            foreach (var type in AppDomain.CurrentDomain.FindInterfaceTypesByAttribute <DynamicProxyAttribute>())
            {
                if (context.HasFiltered(type))
                {
                    continue;
                }

                var dynamicImplmentAttributes = type.GetCustomAttributes <DynamicProxyAttribute>(true).ToList();
                if (dynamicImplmentAttributes.Count > 1)
                {
                    throw new NotSupportedException($"Only one DynamicProxyAttribute can be used for the interface '{type.FullName}'.");
                }
                dynamicImplmentAttributes.First().RegisterService(services, context, type);
            }
        }
Esempio n. 24
0
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            _ = context ?? throw new ArgumentNullException(nameof(declareType));
            _ = declareType ?? throw new ArgumentNullException(nameof(declareType));
            var injectType = this.InjectType ?? DeduceInjectType(declareType);

            switch (this.Lifetime)
            {
            case ServiceLifetime.Singleton:
                services.AddSingleton(injectType, declareType);
                break;

            case ServiceLifetime.Scoped:
                services.AddScoped(injectType, declareType);
                break;

            case ServiceLifetime.Transient:
                services.AddTransient(injectType, declareType);
                break;
            }
        }
Esempio n. 25
0
        /// <summary>
        /// 获取 TTService 最后注册信息
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public IRegisterContext GetRegister(Type serviceType)
        {
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            IRegisterContext registerContext = null;
            ServiceContext   serviceContext  = null;

            if (this.serviceDic.TryGetValue(serviceType, out serviceContext))
            {
                registerContext = new RegisterContext()
                {
                    ServiceType = serviceType,
                    Container   = this,
                    Context     = serviceContext.Get()
                };
            }

            return(registerContext);
        }
Esempio n. 26
0
        public void RegisterServices(IServiceCollection services, IRegisterContext context)
        {
            var connection = context.Configuration.GetConnectionString(ConnectionStringKey);

            if (string.IsNullOrEmpty(connection))
            {
                throw new ApplicationException($"Can not find connection string by key \"{ConnectionStringKey}\".");
            }
            var currentAssembly = Assembly.GetExecutingAssembly().FullName;

            new IdentityServerBuilder(services)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b =>
                {
                    b.UseSqlite(connection, contextbuilder => {
                        contextbuilder.MigrationsAssembly(currentAssembly);
                    });
                };
                options.DefaultSchema = "id4grant";
            });
        }
Esempio n. 27
0
 public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
 {
     _ = declareType ?? throw new ArgumentNullException(nameof(declareType));
     services.AddScoped(declareType, (sp) =>
     {
         var ctor = declareType.GetConstructor(new Type[] { typeof(IMongoDatabase) });
         if (ctor == null)
         {
             throw new ArgumentException($"Can not find constructor with '{typeof(IMongoDatabase).FullName}' argument in [{declareType.FullName}].");
         }
         var clientFactory = sp.GetRequiredService <IMongoClientFactory>();
         var client        = clientFactory.Create(ConnectionStringKey);
         var database      = client.GetDatabase(DataBaseName);
         return(ctor.Invoke(new object[] { database }));
     });
     // add mongo context
     services.AddScoped(sp => sp.GetService(declareType) as MongoContext);
     if (RegisterEntityStore)
     {
         AddEntityStoresInternal(services, declareType);
     }
 }
Esempio n. 28
0
 public GenericControllerFeatureProvider(IRegisterContext registerContext)
 {
     RegisterContext = registerContext;
 }
        public override void RegisterService(IServiceCollection services, IRegisterContext context, Type declareType)
        {
            var method = typeof(HostedServiceAttribute).GetMethod(nameof(AddHostedService), BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(declareType);

            method.Invoke(this, new object[] { services });
        }
Esempio n. 30
0
 public void RegisterServices(IServiceCollection services, IRegisterContext context)
 {
     _ = context ?? throw new ArgumentNullException(nameof(context));
     RegisterController(services, context);
     RegisterHttpContext(services);
 }