public IEnumerable <IComponentRegistration> RegistrationsFor( AutofacService service, Func <AutofacService, IEnumerable <IComponentRegistration> > registrationAccessor) { Guard.NotNull("registrationAccessor", registrationAccessor); var typedService = service as IServiceWithType; if (typedService == null || !typedService.ServiceType .FindInterfaces(TypesHelper.IsOpenGenericType, typeof(IDataAdapterFactoryAdapter <>)).Any()) { return(Enumerable.Empty <IComponentRegistration>()); } if (typeof(IDataSourceAdapterFactoryAdapter).Equals(typedService.ServiceType)) { return(AdaptFactories(typeof(IDataSourceAdapterFactory <>), typeof(DataSourceAdapterFactoryAdapter <>), typedService, registrationAccessor)); } else if (typeof(IDataSinkAdapterFactoryAdapter).Equals(typedService.ServiceType)) { return(AdaptFactories(typeof(IDataSinkAdapterFactory <>), typeof(DataSinkAdapterFactoryAdapter <>), typedService, registrationAccessor)); } else { return(Enumerable.Empty <IComponentRegistration>()); } }
public App(AutofacService autofacService) { InitializeComponent(); AppContainer.GlobalContainer = autofacService.CreateContainer(); MainPage = new MainPage(); }
public static void Write(Log log) { if (log == null) { return; } var slt = AutofacService.Resolve <ILogService>().Insert(log); }
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Autofac AutofacService autofacService = new AutofacService(); autofacService.RegisterServices(); _containerProvider = new ContainerProvider(autofacService.ContainerBuilder.Build()); }
public static List <Banner> GetBannerList(EnumBannerPos pos) { var list = AutofacService.Resolve <IBannerService>().GetBannerListByPosAsync(pos); if (list != null && list.Count > 0) { return(list); } list = AutofacService.Resolve <IBannerService>().GetBannerListByPosAsync(EnumBannerPos.Index); // 如果页面没有banner配置,默认给index的banner配置 return(list ?? new List <Instart.Models.Banner>()); }
public void Configuration(IAppBuilder app) { using (ChannelsContext con = new ChannelsContext()) { con.Database.CreateIfNotExists(); } AutofacService service = new AutofacService(); GlobalConfiguration.Configuration.UseSqlServerStorage("ChannelsContext"); app.UseHangfireDashboard(); app.UseHangfireServer(); RecurringJob.RemoveIfExists("RSSFeed"); RecurringJob.AddOrUpdate("RSSFeed", () => ParseRSS(), Cron.MinuteInterval(2)); }
/// <summary> /// /// </summary> /// <param name="services"></param> public IServiceProvider ConfigureServices(IServiceCollection services) { //配置跨域处理 services.AddCors(options => { options.AddPolicy("AllowAnyOrigin", builder => { builder.AllowAnyOrigin() //允许任何来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); services.AddSession(options => { options.Cookie.HttpOnly = true; options.IdleTimeout = TimeSpan.FromSeconds(7200); }); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Description = "Tingli-作者", Version = "Version 1.0", Title = "微信API文档" }); var basePath = AppContext.BaseDirectory; var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML"; var xmlPath = Path.Combine(basePath, commentsFileName); options.IncludeXmlComments(xmlPath); options.OperationFilter <AssignOperationVendorExtensions>(); }); services.AddDistributedMemoryCache(); services.AddMvc(options => options.Filters.Add <GlobalExceptionAttribute>()) .AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss.fff"; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); return(AutofacService.RegisterAutofac(services, "Stack.WeChat.Contracts", "Stack.WeChat.Service")); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { this.ActionName = filterContext.ActionDescriptor.ActionName; this.ControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; IDictionary <string, object> dic = filterContext.ActionParameters; string extra = string.Empty; if (dic != null && dic.Count > 0) { this.ActionParameters = JsonConvert.SerializeObject(dic); try { string pattern = "\"Id\":(\\d+),"; if (Regex.IsMatch(this.ActionParameters, pattern)) { var match = Regex.Match(this.ActionParameters, pattern); int id = Int32.Parse(match.Groups[1].Value); if (id > 0) { extra = "[修改]"; } else { extra = "[添加]"; } } } catch { } } AutofacService.Resolve <ILogService>().Insert(new Log { Title = this.Title + extra, Remark = this.Remark, ActionName = this.ActionName, ControllerName = this.ControllerName, ActionParameters = this.ActionParameters, CreateTime = DateTime.Now, UserId = CookieData.CurrentUser == null ? 0 : CookieData.CurrentUser.UserId, UserName = CookieData.CurrentUser == null ? "" : CookieData.CurrentUser.UserName }); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <NsDb>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLServer"))); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, x => { x.LoginPath = new PathString("/login"); x.AccessDeniedPath = new PathString("/error"); }); AutofacService autofac = new AutofacService(); return(autofac.RegisterAutofac(services)); }
public IEnumerable<IComponentRegistration> RegistrationsFor( AutofacService service, Func<AutofacService, IEnumerable<IComponentRegistration>> registrationAccessor) { Guard.NotNull("registrationAccessor", registrationAccessor); var typedService = service as IServiceWithType; if (typedService == null || !typedService.ServiceType .FindInterfaces(TypesHelper.IsOpenGenericType, typeof(IDataAdapterFactoryAdapter<>)).Any()) return Enumerable.Empty<IComponentRegistration>(); if (typeof(IDataSourceAdapterFactoryAdapter).Equals(typedService.ServiceType)) { return AdaptFactories(typeof(IDataSourceAdapterFactory<>), typeof(DataSourceAdapterFactoryAdapter<>), typedService, registrationAccessor); } else if (typeof(IDataSinkAdapterFactoryAdapter).Equals(typedService.ServiceType)) { return AdaptFactories(typeof(IDataSinkAdapterFactory<>), typeof(DataSinkAdapterFactoryAdapter<>), typedService, registrationAccessor); } else { return Enumerable.Empty<IComponentRegistration>(); } }
public static List <Course> GetCourseList() { return((AutofacService.Resolve <ICourseService>().GetRecommendListAsync(3)) ?? new List <Instart.Models.Course>()); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { DbContextOption.CommandString = Configuration.GetConnectionString("CommandDB"); DbContextOption.QueryString = Configuration.GetConnectionString("QueryDB"); #region Auth //将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的 services.Configure <JwtSettings>(Configuration.GetSection("JwtSettings")); //由于初始化的时候我们就需要用,所以使用Bind的方式读取配置 //将配置绑定到JwtSettings实例中 var jwtSettings = new JwtSettings(); Configuration.Bind("JwtSettings", jwtSettings); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters { NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role, //Token颁发机构 ValidIssuer = jwtSettings.Issuer, //颁发给谁 ValidAudience = jwtSettings.Audience, //这里的key要进行加密,需要引用Microsoft.IdentityModel.Tokens IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)) /***********************************TokenValidationParameters的参数默认值***********************************/ // RequireSignedTokens = true, // SaveSigninToken = false, // ValidateActor = false, // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。 // ValidateAudience = true, // ValidateIssuer = true, // ValidateIssuerSigningKey = false, // 是否要求Token的Claims中必须包含Expires // RequireExpirationTime = true, // 允许的服务器时间偏移量 // ClockSkew = TimeSpan.FromSeconds(300), // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比 // ValidateLifetime = true }; }); #endregion services.AddMvc(option => { option.Filters.Add(new GlobalExceptionFilter()); }); services.AddSwaggerGen(c => { //c.OperationFilter<SwaggerFileUploadFilter>();//增加文件过滤处理 //var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, }; //c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致 //c.AddSecurityRequirement(security); c.SwaggerDoc("v1", new Info { Version = "v1", Title = "SoulVoice API", Description = "For SoulVoice Web&&App", }); //var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, }; //c.(security); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); //c.OperationFilter<HttpHeaderFilter>(); }); services.AddAutoMapper(); return(AutofacService.InitIoC(services)); }
public override void OnAuthorization(AuthorizationContext filterContext) { if (WebAppSettings.IsDevelop) { var testUser = new LoginUser { UserId = 10000, UserName = "******", NickName = "liufei", Avatar = "", }; CookieData.CurrentUser = testUser; filterContext.HttpContext.Session[WebAppSettings.SessionName] = testUser; return; } var session = filterContext.HttpContext.Session[WebAppSettings.SessionName]; if (session == null) { var cookie = filterContext.HttpContext.Request.Cookies[WebAppSettings.CookieName]; if (cookie == null) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "account", action = "login", area = "manage" })); return; } var userId = Common.DesHelper.Decrypt(cookie.Value, WebAppSettings.DesEncryptKey).ToInt32OrDefault(0); if (userId == 0) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "account", action = "login", area = "manage" })); return; } var user = AutofacService.Resolve <IUserService>().GetById(userId); if (user == null) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "account", action = "login", area = "manage" })); return; } var loginUser = new LoginUser { UserId = user.Id, UserName = user.UserName, NickName = user.NickName, Avatar = user.Avatar, }; CookieData.CurrentUser = loginUser; filterContext.HttpContext.Session[WebAppSettings.SessionName] = loginUser; } }
/// <summary> /// IServiceProvider /// </summary> /// <param name="services"></param> /// <returns></returns> public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); options.SerializerSettings.DateFormatString = "yyyy-MM-dd"; }); #region Swagger services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Version = "Version 1.0", Title = "TrunkCoreDemo的API文档", Description = "Dylan作者" }); var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML"; var basePath = AppContext.BaseDirectory; var xmlPath = Path.Combine(basePath, commentsFileName); options.IncludeXmlComments(xmlPath); options.OperationFilter <AssignOperationVendorExtensions>(); }); #endregion //向容器内注入数据库 //var connectionStrings = Configuration.GetConnectionString("MYSQLWALIUJR_SYS"); //services.AddDbContext<WALIUJR_SYSContext>(options => options.UseSqlServer(connectionStrings)); #region Autofac DI注入 第一种 //说明:ConfigureServices返回void,通过构造函数来获取 //services.AddTransient<IDemoService, DemoService>(); #endregion #region Autofac DI注入 第二种 //说明:ConfigureServices返回IServiceProvider,通过接口属性来获取 //services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>()); //var builder = new ContainerBuilder(); //builder.RegisterType<DemoService>().As<IDemoService>().InstancePerLifetimeScope().PropertiesAutowired(); //builder.RegisterType(typeof(ValuesController)).InstancePerLifetimeScope().PropertiesAutowired(); //builder.Populate(services); //return new AutofacServiceProvider(builder.Build()); #endregion #region Autofac DI注入 第三种 //说明:ConfigureServices返回IServiceProvider,通过接口属性来获取,自动获取Controller的属性 //services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>()); //var assembly = this.GetType().GetTypeInfo().Assembly; //var manager = new ApplicationPartManager(); //manager.ApplicationParts.Add(new AssemblyPart(assembly)); //manager.FeatureProviders.Add(new ControllerFeatureProvider()); //var feature = new ControllerFeature(); //manager.PopulateFeature(feature); //var builder = new ContainerBuilder(); //builder.RegisterType<ApplicationPartManager>().AsSelf().SingleInstance(); //builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired(); //builder.Populate(services); //Assembly iface = Assembly.Load("TrunkCoreDemo.Service"); //Assembly service = Assembly.Load("TrunkCoreDemo.Contracts"); //builder.RegisterAssemblyTypes(iface, service) // .Where(t => t.Name.EndsWith("Service")) // .AsImplementedInterfaces() // .InstancePerLifetimeScope(); //return new AutofacServiceProvider(builder.Build()); #endregion #region Autofac DI注入 第四种 //说明:ConfigureServices返回IServiceProvider,通过接口属性来获取, //Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(q => q.FullName.Contains("Trunk")).ToArray(); //var types = Assembly.GetEntryAssembly().GetReferencedAssemblies(); //String baseDir = AppContext.BaseDirectory; //String basePath2 = Path.GetDirectoryName(typeof(Program).Assembly.Location); //DirectoryInfo dirInfo = new DirectoryInfo(baseDir); //var fileInfo = dirInfo.GetFiles().Where(q => q.FullName.Contains(".Service")).FirstOrDefault(); //services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>()); //var assembly = this.GetType().GetTypeInfo().Assembly; //var manager = new ApplicationPartManager(); //manager.ApplicationParts.Add(new AssemblyPart(assembly)); //manager.FeatureProviders.Add(new ControllerFeatureProvider()); //var feature = new ControllerFeature(); //manager.PopulateFeature(feature); //var builder = new ContainerBuilder(); //builder.RegisterType<ApplicationPartManager>().AsSelf().SingleInstance(); //builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired(); //builder.Populate(services); //var assemblys = Assembly.LoadFrom(fileInfo.FullName); //var baseType = typeof(IDependency); //builder.RegisterAssemblyTypes(assemblys) // .Where(m => baseType.IsAssignableFrom(m) && m != baseType) // .AsImplementedInterfaces().InstancePerLifetimeScope(); //return new AutofacServiceProvider(builder.Build()); #endregion return(AutofacService.RegisterAutofac(services, "DMS.EntityFrameworkCore.Contracts", "DMS.EntityFrameworkCore.Service")); }