public static IMvcCoreBuilder AddIdentityUtilsAuthenticationControllerAssemblyPart(this IMvcCoreBuilder builder) { builder.RemoveIdentityUtilsAuthenticationControllerAssemblyPart(); builder.AddApplicationPart(controllersAssembly); return(builder); }
public static IMvcCoreBuilder AddWebApiCore(this IServiceCollection services, params Assembly[] controllersAssemblies) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (controllersAssemblies == null) { throw new ArgumentNullException(nameof(controllersAssemblies)); } controllersAssemblies = controllersAssemblies.Any() ? controllersAssemblies : new[] { Assembly.GetCallingAssembly() }; IMvcCoreBuilder builder = services.AddMvcCore() .AddJsonFormatters(); controllersAssemblies.ToList().ForEach(asm => { builder.AddApplicationPart(asm); }); builder.AddControllersAsServices(); return(builder); }
public static IMvcCoreBuilder AddWebApiCore(this IServiceCollection services, params Assembly[] controllersAssemblies) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (controllersAssemblies == null) { throw new ArgumentNullException(nameof(controllersAssemblies)); } controllersAssemblies = AssemblyContainer.Current.AssembliesWithDefaultAssemblies(controllersAssemblies); IMvcCoreBuilder builder = services.AddMvcCore() .AddJsonFormatters(); controllersAssemblies.ToList().ForEach(asm => { builder.AddApplicationPart(asm); }); builder.AddControllersAsServices(); return(builder); }
public static IMvcCoreBuilder AddWebApiCore(this IServiceCollection services, IDependencyManager dependencyManager, params Assembly[] controllersAssemblies) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (controllersAssemblies == null) { throw new ArgumentNullException(nameof(controllersAssemblies)); } controllersAssemblies = AssemblyContainer.Current.AssembliesWithDefaultAssemblies(controllersAssemblies); IMvcCoreBuilder builder = services.AddMvcCore() .AddJsonFormatters() .AddAuthorization() // ToDo: Needs enhancements! .AddFormatterMappings() //.SetCompatibilityVersion(CompatibilityVersion.Version_2_1) // ToDo .AddDataAnnotations(); foreach (Assembly asm in controllersAssemblies) { builder.AddApplicationPart(asm); } dependencyManager.RegisterAssemblyTypes(controllersAssemblies, t => (t.GetCustomAttribute <ControllerAttribute>(inherit: true /*ApiControllerAttribute*/) != null || t.GetCustomAttribute <RouteAttribute>() != null) && t.GetCustomAttribute <NonControllerAttribute>() == null, lifeCycle: DependencyLifeCycle.Transient); builder.Services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); return(builder); }
public static IMvcCoreBuilder AddWebApiCore(this IServiceCollection services, IDependencyManager dependencyManager, params Assembly[] controllersAssemblies) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (controllersAssemblies == null) { throw new ArgumentNullException(nameof(controllersAssemblies)); } controllersAssemblies = AssemblyContainer.Current.AssembliesWithDefaultAssemblies(controllersAssemblies); IMvcCoreBuilder builder = services.AddMvcCore() .AddJsonFormatters(); controllersAssemblies.ToList().ForEach(asm => { builder.AddApplicationPart(asm); }); dependencyManager.RegisterAssemblyTypes(controllersAssemblies, t => t.GetCustomAttribute <ControllerAttribute>() != null, lifeCycle: DependencyLifeCycle.Transient); builder.Services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); return(builder); }
private static void AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder, Assembly assembly, string systemName, string filename) { try { //we can now register the plugin definition Log.Information("Adding to ApplicationParts: '{0}'", systemName); mvcCoreBuilder.AddApplicationPart(assembly); var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false); foreach (var relatedAssembly in relatedAssemblies) { var applicationPartFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly); foreach (var part in applicationPartFactory.GetApplicationParts(relatedAssembly)) { mvcCoreBuilder.PartManager.ApplicationParts.Add(part); } } } catch (Exception ex) { Log.Error(ex, "PluginManager"); throw new InvalidOperationException($"The plugin directory for the {systemName} file exists in a folder outside of the allowed grandnode folder hierarchy - exception because of {filename} - exception: {ex.Message}"); } }
/// <summary> /// Add multiple assemblies as application parts to the <paramref name="mvcBuilder"/> /// </summary> /// <param name="mvcBuilder">The builder the application parts are added to.</param> /// <param name="viewAssemblies">The <see cref="Assembly"/>'s to add as application parts.</param> /// <returns>The <paramref name="mvcBuilder"/>.</returns> public static IMvcCoreBuilder AddViewsApplicationParts(this IMvcCoreBuilder mvcBuilder, Assembly[] viewAssemblies) { foreach (var assembly in viewAssemblies) { mvcBuilder.AddApplicationPart(assembly); } return(mvcBuilder); }
static IMvcCoreBuilder AddApplicationParts(this IMvcCoreBuilder mvc, IEnumerable <Assembly> assemblies) { foreach (var assembly in assemblies) { mvc = mvc.AddApplicationPart(assembly); } return(mvc); }
public static IMvcCoreBuilder AddUsersModule( this IMvcCoreBuilder builder, string databaseName, CheckTextForProfanity profanityCheck ) { EventMappings.MapEventTypes(); builder.Services.AddSingleton( c => new UserProfileCommandService( new EsAggregateStore( c.GetRequiredService <IEventStoreConnection>() ), profanityCheck ) ) .AddSingleton <GetUsersModuleSession>( c => { var store = c.GetRequiredService <IDocumentStore>(); store.CheckAndCreateDatabase(databaseName); IAsyncDocumentSession GetSession() => store.OpenAsyncSession(databaseName); return(GetSession); } ) .AddSingleton( c => { var getSession = c.GetRequiredService <GetUsersModuleSession>(); return(new SubscriptionManager( c.GetRequiredService <IEventStoreConnection>(), new RavenDbCheckpointStore( () => getSession(), SubscriptionName ), SubscriptionName, new RavenDbProjection <UserDetails>( () => getSession(), UserDetailsProjection.GetHandler ) )); } ) .AddSingleton <AuthService>(); builder.AddApplicationPart(typeof(UsersModule).Assembly); return(builder); }
public static IMvcCoreBuilder AddTestControllers(this IMvcCoreBuilder builder) { var path = Path.Combine(AppContext.BaseDirectory, "nhitomi.Tests.dll"); if (File.Exists(path)) { builder = builder.AddApplicationPart(Assembly.LoadFrom(path)); } return(builder); }
public static IMvcCoreBuilder AddAdsModule( this IMvcCoreBuilder builder, string databaseName, ICurrencyLookup currencyLookup, UploadFile uploadFile ) { EventMappings.MapEventTypes(); builder.Services.AddSingleton( c => new ClassifiedAdsCommandService( c.GetAggregateStore(), currencyLookup, uploadFile ) ); builder.Services.AddSingleton( c => { var store = c.GetRavenStore(); store.CheckAndCreateDatabase(databaseName); IAsyncDocumentSession GetSession() => c.GetRavenStore() .OpenAsyncSession(databaseName); return(new SubscriptionManager( c.GetEsConnection(), new RavenDbCheckpointStore( GetSession, SubscriptionName ), SubscriptionName, StreamName.AllStream, new RavenDbProjection <ClassifiedAdDetails>( GetSession, ClassifiedAdDetailsProjection.GetHandler ), new RavenDbProjection <MyClassifiedAds>( GetSession, MyClassifiedAdsProjection.GetHandler ) )); } ); builder.AddApplicationPart(typeof(AdsModule).Assembly); return(builder); }
/// <summary> /// Adds PineBlog Razor Pages services to the services collection. /// </summary> /// <param name="builder">The Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder.</param> public static IMvcCoreBuilder AddPineBlogRazorPages(this IMvcCoreBuilder builder) { ConfigureServices(builder.Services); builder.AddApplicationPart(typeof(Controllers.FileController).Assembly); builder.AddRazorPages(SetRazorPagesOptions); builder.AddMvcOptions(options => { options.Filters.Add <PineBlogViewDataAsyncPageFilter>(); }); builder.AddFluentValidation(); return(builder); }
private static void AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder, Assembly assembly, string systemName, string filename) { try { //we can now register the plugin definition Log.Information("Adding to ApplicationParts: '{0}'", systemName); mvcCoreBuilder.AddApplicationPart(assembly); } catch (Exception ex) { Log.Error(ex, "PluginManager"); throw new InvalidOperationException($"The plugin directory for the {systemName} file exists in a folder outside of the allowed grandnode folder hierarchy - exception because of {filename} - exception: {ex.Message}"); } }
public static IMvcCoreBuilder AddGitLfs(this IMvcCoreBuilder builder) { builder.AddJsonFormatters(); builder.AddApplicationPart(typeof(LfsConstants).GetTypeInfo().Assembly); builder.AddMvcOptions(options => { options.Filters.Add(new ProducesAttribute(LfsConstants.LfsMediaType.MediaType.Buffer)); options.Filters.Add(new TypeFilterAttribute(typeof(BasicAuthFilter))); JsonOutputFormatter jsonOutput = options.OutputFormatters.OfType <JsonOutputFormatter>().First(); jsonOutput.SupportedMediaTypes.Add(LfsConstants.LfsMediaType); JsonInputFormatter jsonInput = options.InputFormatters.OfType <JsonInputFormatter>().First(); jsonInput.SupportedMediaTypes.Add(LfsConstants.LfsMediaType); }); return(builder); }
public static IMvcCoreBuilder AddAdsModule( this IMvcCoreBuilder builder, string databaseName) { EventMappings.MapEventTypes(); builder.Services.AddSingleton( c => new InternalAssociateCommandService( new EsAggregateStore(c.GetEsConnection()) ) ); builder.Services.AddSingleton( c => { var store = c.GetRavenStore(); store.CheckAndCreateDatabase(databaseName); IAsyncDocumentSession GetSession() => c.GetRavenStore() .OpenAsyncSession(databaseName); return(new SubscriptionManager( c.GetEsConnection(), new RavenDbCheckpointStore( GetSession, SubscriptionName ), SubscriptionName, new RavenDbProjection <ReadModels.InternalAssociateDetails>( GetSession, InternalAssociateDetailsProjection.GetHandler ), new RavenDbProjection <ReadModels.MyInternalAssociateDetails>( GetSession, MyClassifiedAdsProjection.GetHandler ) )); } ); builder.AddApplicationPart(typeof(AdsModule).Assembly); return(builder); }
/// <summary> /// Adds PineBlog Razor Pages services to the services collection. /// </summary> /// <param name="builder">The Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder.</param> public static IMvcCoreBuilder AddPineBlogRazorPages(this IMvcCoreBuilder builder) { ConfigureServices(builder.Services); builder.AddApplicationPart(typeof(Controllers.FileController).Assembly); builder.AddRazorPages(option => { option.Conventions.AuthorizeAreaFolder("Admin", "/"); option.Conventions.AddAreaPageRoute("Blog", "/Post", PineBlogConstants.BlogAreaPath + "/{*slug}"); }); builder.AddMvcOptions(options => { options.Filters.Add <PineBlogViewDataAsyncPageFilter>(); }); builder.AddFluentValidation(); return(builder); }
// Methods public static void AddAssemblyController(this IMvcCoreBuilder builder, string controllerFilename) { #region Contracts if (builder == null) { throw new ArgumentException(); } if (string.IsNullOrEmpty(controllerFilename) == true) { throw new ArgumentException(); } #endregion // AssemblyFileList var assemblyFileList = FileHelper.GetAllFile(controllerFilename); if (assemblyFileList == null) { throw new InvalidOperationException(); } // AddAssemblyController foreach (var assemblyFile in assemblyFileList) { // Assembly Assembly assembly = null; try { assembly = Assembly.LoadFile(assemblyFile.FullName); if (assembly == null) { throw new InvalidOperationException(); } } catch { continue; } // Register builder.AddApplicationPart(assembly); } }
public static IWebHostBuilder ForFullNode(this IWebHostBuilder hostBuilder, FullNode fullNode) { hostBuilder.ConfigureServices(s => { IMvcCoreBuilder mvcBuilder = s.AddMvcCore(o => { o.ModelBinderProviders.Insert(0, new DestinationModelBinder()); o.ModelBinderProviders.Insert(0, new MoneyModelBinder()); }); // Include all feature assemblies for action discovery otherwise RPC actions will not execute // https://stackoverflow.com/questions/37725934/asp-net-core-mvc-controllers-in-separate-assembly foreach (Assembly assembly in fullNode.Services.Features.OfType <FullNodeFeature>().Select(x => x.GetType().GetTypeInfo().Assembly).Distinct()) { mvcBuilder.AddApplicationPart(assembly); } }); return(hostBuilder); }
public static IMvcCoreBuilder AddGitLfs(this IMvcCoreBuilder builder) { builder.AddNewtonsoftJson(); builder.AddApplicationPart(typeof(LfsConstants).GetTypeInfo().Assembly); builder.AddMvcOptions(options => { options.Filters.Add(new ProducesAttribute(LfsConstants.LfsMediaType.MediaType.Buffer)); options.Filters.Add(new TypeFilterAttribute(typeof(BasicAuthFilter))); foreach (InputFormatter input in options.InputFormatters.OfType <NewtonsoftJsonInputFormatter>()) { input.SupportedMediaTypes.Add(LfsConstants.LfsMediaType); } foreach (OutputFormatter output in options.OutputFormatters.OfType <NewtonsoftJsonOutputFormatter>()) { output.SupportedMediaTypes.Add(LfsConstants.LfsMediaType); } }); return(builder); }
/// <summary> /// Perform file deply /// </summary> /// <param name="plug">Plugin file info</param> /// <param name="applicationPartManager">Application part manager</param> /// <returns>Assembly</returns> private static Assembly AddApplicationPart(FileInfo plug, IMvcCoreBuilder mvcCoreBuilder, GrandConfig config) { if (plug.Directory == null || plug.Directory.Parent == null) { throw new InvalidOperationException("The plugin directory for the " + plug.Name + " file exists in a folder outside of the allowed grandnode folder hierarchy"); } var _plug = config.PluginShadowCopy ? ShadowCopyFile(plug, Directory.CreateDirectory(_shadowCopyFolder.FullName)) : plug; try { Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(_plug.FullName); //we can now register the plugin definition Debug.WriteLine("Adding to ApplicationParts: '{0}'", assembly.FullName); mvcCoreBuilder.AddApplicationPart(assembly); return(assembly); } catch (Exception ex) { throw new InvalidOperationException($"The plugin directory for the {plug.Name} file exists in a folder outside of the allowed grandnode folder hierarchy - exception because of {plug.FullName} - exception: {ex.Message}"); } }
public static IServiceCollection AddMyBlogEngine(this IServiceCollection services, IConfiguration configuration, IMvcCoreBuilder mvc) { // Get settings for next steps var settings = configuration.Get <Settings>(); services.AddLocalization(); // Add Controllers to the MVC pipeline mvc?.AddApplicationPart(typeof(SetupExtensions).Assembly) .AddMvcLocalization(); // Options services.Configure <Settings>(configuration); // Data context services.AddDbContext <DataContext>(options => options.UseSqlServer(configuration.GetConnectionString(ConnectionString))); //services.AddScoped<DataContext>(_ => // new DataContext(configuration.GetConnectionString(ConnectionString))); // HTTP Accessor services.AddHttpContextAccessor(); // Session services.AddSession(); #region Authentication // activate the authentication var authBuilder = services.AddAuthentication(Constants.SignInScheme) .AddCookie(Constants.SignInScheme, options => { options.LoginPath = "/Authentication"; }); // Microsoft authentication if (settings.MicrosoftAccountAuthentication.Active) { authBuilder = authBuilder.AddMicrosoftAccount(options => { options.SignInScheme = Constants.SignInScheme; options.ClientId = settings.MicrosoftAccountAuthentication.ClientId; options.ClientSecret = settings.MicrosoftAccountAuthentication.ClientSecret; }); } // Facebook authentication if (settings.FacebookAuthentication.Active) { authBuilder = authBuilder.AddFacebook(options => { options.SignInScheme = Constants.SignInScheme; options.ClientId = settings.FacebookAuthentication.ClientId; options.ClientSecret = settings.FacebookAuthentication.ClientSecret; }); } // Twitter authentication if (settings.TwitterAuthentication.Active) { authBuilder = authBuilder.AddTwitter(options => { options.SignInScheme = Constants.SignInScheme; options.ConsumerKey = settings.TwitterAuthentication.ClientId; options.ConsumerSecret = settings.TwitterAuthentication.ClientSecret; }); } // Google authentication if (settings.GoogleAuthentication.Active) { authBuilder = authBuilder.AddGoogle(options => { options.SignInScheme = Constants.SignInScheme; options.ClientId = settings.GoogleAuthentication.ClientId; options.ClientSecret = settings.GoogleAuthentication.ClientSecret; }); } #endregion #region Services // DataService services.AddScoped <DataService>(); // Feeds services.AddScoped <FeedService>(); // Files service services.AddScoped <FilesService>(); // Mails services.AddScoped <MailService>(); // User service services.AddScoped <UserService>(); // Users settings services.AddScoped <UserSettingsService>(); // Layout service to obtain a model services.AddScoped <LayoutService>(); #endregion #region Metaweblog services.AddScoped <MetaWeblogService>(); #endregion return(services); }
public static IMvcCoreBuilder AddDownlink(this IMvcCoreBuilder builder, Action <IDownlinkBuilder> configure, DownlinkBuilderOptions opts) { builder.AddApplicationPart(typeof(DownlinkBuilder).Assembly); BuildDownlink(builder.Services, configure, opts); return(builder); }
private static void AddActiveRouteImpl <TController, TFeature, TFeatureOptions>(IMvcCoreBuilder mvcBuilder) where TFeature : class, IDynamicFeature where TFeatureOptions : class { // Add [DynamicController(typeof(TComponentOptions))] if not present if (!typeof(TController).HasAttribute <DynamicControllerAttribute>()) { var attribute = new DynamicControllerAttribute(typeof(TFeatureOptions)); TypeDescriptor.AddAttributes(typeof(TController), attribute); var attributes = TypeDescriptor.GetAttributes(typeof(TController)); if (!attributes.Contains(attribute)) { throw new InvalidOperationException("Could not add attribute dynamically on this runtime."); } } // See: https://github.com/aspnet/Mvc/issues/5992 mvcBuilder.AddApplicationPart(typeof(TController).Assembly); mvcBuilder.ConfigureApplicationPartManager(x => { x.ApplicationParts.Add(new DynamicControllerApplicationPart(new[] { typeof(TController).GetTypeInfo() })); }); var componentDescriptor = ServiceDescriptor.Singleton(r => { var component = Instancing.CreateInstance <TFeature>(); component.GetRouteTemplate = () => { var o = r.GetRequiredService <IOptionsMonitor <TFeatureOptions> >(); return(o.CurrentValue is IFeatureNamespace ns ? ns.RootPath ?? string.Empty : string.Empty); }; return(component); }); mvcBuilder.Services.Replace(componentDescriptor); mvcBuilder.Services.AddTransient <IDynamicFeature>(r => { // cached singleton var component = r.GetService <TFeature>(); // each resolution, we could be discovering a different controller that needs hydration into its type for (var i = 0; i < component.ControllerTypes.Count; i++) { var controllerType = component.ControllerTypes[i]; if (controllerType.IsGenericType && controllerType.Name == typeof(TController).Name) { component.ControllerTypes[i] = typeof(TController); } } return(component); }); mvcBuilder.AddAuthorization(x => { if (x.GetPolicy(Constants.Security.Policies.NoPolicy) == null) { x.AddPolicy(Constants.Security.Policies.NoPolicy, b => { b.RequireAssertion(context => true); }); } }); }
/// <summary> /// 动态构建API代码,部分核心代码测试 /// </summary> public void DynamicBuild(IServiceCollection services, IMvcCoreBuilder builder) { var invokeClassType = typeof(EntityApiBindTestService); //var invokeClassType = typeof(StaticApiBindTestService); var invokeMethodName = "TestApiAsync";//TestApiAsync or TestApi var invokeMethodInfo = invokeClassType.GetMethod(invokeMethodName); Console.WriteLine("======== DynamicBuild Start ========"); Console.WriteLine($"invokeClassType: {invokeClassType.Name}"); Console.WriteLine($"invokeMethodName: {invokeMethodName}"); Console.WriteLine($"invokeMethod ReturnType: {invokeMethodInfo.ReturnType.Name}"); #region 构造程序集 AssemblyName dynamicApiAssembly = new AssemblyName("DynamicTests"); //AppDomain currentDomain = Thread.GetDomain(); AssemblyBuilder dynamicAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(dynamicApiAssembly, AssemblyBuilderAccess.RunAndCollect); //动态创建模块 ModuleBuilder mb = dynamicAssemblyBuilder.DefineDynamicModule(dynamicApiAssembly.Name); //动态创建类 XXController var controllerClassName = $"DynamicTestController"; TypeBuilder tb = mb.DefineType(controllerClassName, TypeAttributes.Public, typeof(ControllerBase) /*typeof(Controller)*/); //var t1 = typeof(ApiController); //tb.SetCustomAttribute(new CustomAttributeBuilder(t1.GetConstructor(new Type[] { typeof(string) }), new object[] })); var t2 = typeof(RouteAttribute); tb.SetCustomAttribute(new CustomAttributeBuilder(t2.GetConstructor(new Type[] { typeof(string) }), new object[] { $"myapi/[controller]" })); //私有变量 var fbServiceProvider = tb.DefineField("_serviceProvider", typeof(IServiceProvider), FieldAttributes.Private | FieldAttributes.InitOnly); #endregion #region 设置构造函数 //设置构造函数 var ctorBuilder = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new[] { typeof(IServiceProvider) }); var ctorIl = ctorBuilder.GetILGenerator(); ctorIl.Emit(OpCodes.Ldarg, 0); //Define the reflection ConstructorInfor for System.Object ConstructorInfo conObj = typeof(object).GetConstructor(new Type[0]); ctorIl.Emit(OpCodes.Call, conObj);//调用base的默认ctor ctorIl.Emit(OpCodes.Nop); ctorIl.Emit(OpCodes.Nop); ctorIl.Emit(OpCodes.Ldarg, 0); ctorIl.Emit(OpCodes.Ldarg, 1); ctorIl.Emit(OpCodes.Stfld, fbServiceProvider); ctorIl.Emit(OpCodes.Ret); #endregion #region 设置方法 //设置方法 MethodBuilder setPropMthdBldr = tb.DefineMethod("Tests", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, invokeMethodInfo.ReturnType, //返回类型 new[] { typeof(string), typeof(int) }//输入参数 ); //添加标签 var t2_3 = typeof(SwaggerOperationAttribute); var tagName = new[] { $"DynamicTest:Test" }; var tagAttrBuilder = new CustomAttributeBuilder(t2_3.GetConstructor(new Type[] { typeof(string), typeof(string) }), new object[] { (string)null, (string)null }, new[] { t2_3.GetProperty("Tags") }, new[] { tagName }); setPropMthdBldr.SetCustomAttribute(tagAttrBuilder); var t2_4 = typeof(RouteAttribute); //var routeName = apiBindInfo.Value.ApiBindAttribute.Name.Split('.')[0]; var apiPath = $"/mywxapi/dynamic"; var routeAttrBuilder = new CustomAttributeBuilder(t2_4.GetConstructor(new Type[] { typeof(string) }), new object[] { apiPath } /*, new[] { t2_2.GetProperty("Name") }, new[] { routeName }*/); setPropMthdBldr.SetCustomAttribute(routeAttrBuilder); //[HttpGet] var t3 = typeof(HttpGetAttribute); setPropMthdBldr.SetCustomAttribute(new CustomAttributeBuilder(t3.GetConstructor(new Type[0]), new object[0])); //var tFromQuery = typeof(FromQueryAttribute); //pb2.SetCustomAttribute(new CustomAttributeBuilder(tFromQuery.GetConstructor(new Type[0]), new object[0])); ParameterBuilder pb1 = setPropMthdBldr.DefineParameter(1, ParameterAttributes.None, "name"); ParameterBuilder pb2 = setPropMthdBldr.DefineParameter(2, ParameterAttributes.None, "val"); //复制特性 var customAttrs = CustomAttributeData.GetCustomAttributes(invokeMethodInfo); foreach (var item in customAttrs) { if (item.AttributeType == typeof(ApiBindAttribute)) { continue; } var attrBuilder = new CustomAttributeBuilder(item.Constructor, item.ConstructorArguments.Select(z => z.Value).ToArray()); setPropMthdBldr.SetCustomAttribute(attrBuilder); } #endregion #region 设置方法体(Body) //执行具体方法 var il = setPropMthdBldr.GetILGenerator(); LocalBuilder local = il.DeclareLocal(invokeMethodInfo.ReturnType); // create a local variable if (invokeClassType == typeof(EntityApiBindTestService) || !invokeMethodInfo.IsStatic) { //Label lblEnd = il.DefineLabel(); /* 最简洁方法(独立使用) * il.Emit(OpCodes.Nop); * //il.Emit(OpCodes.Ldarg, 0); * il.Emit(OpCodes.Ldarg, 1); * il.Emit(OpCodes.Stloc, local); * il.Emit(OpCodes.Ldloc, local); * il.Emit(OpCodes.Ret); */ //实例方法 il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg, 0); il.Emit(OpCodes.Ldfld, fbServiceProvider); il.Emit(OpCodes.Ldtoken, invokeClassType); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); il.Emit(OpCodes.Callvirt, typeof(IServiceProvider).GetMethod("GetService")); il.Emit(OpCodes.Isinst, invokeClassType); il.Emit(OpCodes.Stloc, 0); il.Emit(OpCodes.Ldloc, 0); il.Emit(OpCodes.Ldarg, 1); il.Emit(OpCodes.Ldarg, 2); il.Emit(OpCodes.Callvirt, invokeMethodInfo); il.Emit(OpCodes.Stloc, local); //il.Emit(OpCodes.Br_S, lblEnd); //il.MarkLabel(lblEnd); il.Emit(OpCodes.Ldloc, local); il.Emit(OpCodes.Ret); } else { //静态方法调用 il.Emit(OpCodes.Nop); // the first one in arguments list il.Emit(OpCodes.Ldarg, 1); // the first one in arguments list il.Emit(OpCodes.Ldarg, 2); il.Emit(OpCodes.Call, invokeMethodInfo); il.Emit(OpCodes.Stloc, local); // set local variable il.Emit(OpCodes.Ldloc, local); // load local variable to stack //il.Emit(OpCodes.Stloc, 1); //Label lbl = il.DefineLabel(); //il.Emit(OpCodes.Br_S, lbl); //il.MarkLabel(lbl); //il.Emit(OpCodes.Ldloc, 1); il.Emit(OpCodes.Ret); } #endregion var t = tb.CreateType(); TypeInfo objectTypeInfo = tb.CreateTypeInfo(); var myType = objectTypeInfo.AsType(); services.AddScoped(myType); builder.AddApplicationPart(mb.Assembly); Console.WriteLine($"\t create type: {myType.Namespace} - {myType.FullName}"); using (var scope = services.BuildServiceProvider().CreateScope()) { var ctrl = scope.ServiceProvider.GetService(myType); Console.WriteLine(ctrl.GetType()); var testMethod = ctrl.GetType().GetMethod("Tests"); Console.WriteLine("testMethod.GetParameters().Count(): " + testMethod.GetParameters().Count()); var result = testMethod.Invoke(ctrl, new object[] { "来自 ApiBindTestService.DynamicBuild() 方法,看到此信息表明自动生成 API 已成功", 1 }); Console.WriteLine("result:" + result); Console.WriteLine("Attrs Name: " + string.Join('|', ctrl.GetType().GetMethod("Tests").GetCustomAttributes().Select(z => z.GetType().Name))); } }
public static IMvcCoreBuilder AddFuxionControllers(this IMvcCoreBuilder me) => me.AddApplicationPart(typeof(CommandController).Assembly);
internal static void ConfigureMvcBuilder(IMvcCoreBuilder builder, IConfiguration configuration) { builder.AddApplicationPart(typeof(DiagnosticController).Assembly); }
/// <summary> /// Registers harpoon controllers into current <see cref="IMvcCoreBuilder"/> /// </summary> /// <param name="mvcBuilder"></param> /// <returns></returns> public static IMvcCoreBuilder AddHarpoonControllers(this IMvcCoreBuilder mvcBuilder) => mvcBuilder.AddApplicationPart(typeof(WebHooksController).Assembly);
public static IMvcCoreBuilder AddPaidServicesModule( this IMvcCoreBuilder builder, string databaseName ) { EventMappings.MapEventTypes(); builder.Services.AddSingleton( c => new OrdersCommandService(c.GetStore()) ); builder.Services.AddSingleton( c => new ClassifiedAdCommandService(c.GetStore()) ); builder.Services.AddSingleton( c => { var store = c.GetRequiredService <IDocumentStore>(); store.CheckAndCreateDatabase(databaseName); const string subscriptionName = "servicesReadModels"; IAsyncDocumentSession GetSession() => c.GetRequiredService <IDocumentStore>() .OpenAsyncSession(databaseName); return(new SubscriptionManager( c.GetRequiredService <IEventStoreConnection>(), new RavenDbCheckpointStore( GetSession, subscriptionName ), subscriptionName, new RavenDbProjection <OrderDraft>( GetSession, DraftOrderProjection.GetHandler ), new RavenDbProjection <CompletedOrder>( GetSession, CompletedOrderProjection.GetHandler ) )); } ); builder.Services.AddSingleton( c => { var connection = c.GetRequiredService <IEventStoreConnection>(); const string subscriptionName = "servicesReactors"; return(new SubscriptionManager( connection, new EsCheckpointStore(connection, subscriptionName), subscriptionName, new OrderReactor( c.GetRequiredService <ClassifiedAdCommandService>() ) )); } ); builder.AddApplicationPart(typeof(PaidServicesModule).Assembly); return(builder); }
public static IMvcCoreBuilder AddScanningControllers(this IMvcCoreBuilder builder) { builder.AddApplicationPart(typeof(ScanningProvider).Assembly); return(builder); }