public App() { InitializeComponent(); //DependencyService.Register<HttpClient>(); //DependencyService.Register<ApiClientProxy>(); AutofacHelper.Initialize(); ////TODO remove in future //var authService = AutofacHelper.Container.Resolve<AuthService>(); //var api = AutofacHelper.Container.Resolve<ApiClientProxy>(); //var response = api.Post("Auth/Login", new Login { UsernameOrEmail = "test", PasswordHash = "P@ssw0rd" }); //var result = ApiClientProxy.ReadAnswer<ApiResponse<string>>(response); //if (result.Code == ApiResponseCode.OK) //{ // authService.Login(result.Value); // MainPage = new NavigationPage(new ResourceView()); //} //else //{ // MainPage = new NavigationPage(new MainPage()); //} MainPage = new NavigationPage(new MainPage()); }
protected override void Load(ContainerBuilder builder) { AutofacHelper.RegisterCqrsTypes <IdentityDetails>(builder); AutofacHelper.RegisterCqrsTypes <UserDetailsModule>(builder); AutofacHelper.RegisterCqrsTypes <ApplicationModule>(builder); AutofacHelper.RegisterAutoMapperProfiles <IdentityDetails>(builder); AutofacHelper.RegisterAutoMapperProfiles <ApplicationModule>(builder); AutofacHelper.RegisterAutoMapperProfiles <UserDetailsModule>(builder); // Repositories builder.RegisterType <UserRepository>() .As <IUserRepository>() .InstancePerLifetimeScope(); builder.RegisterType <ClaimsManager>() .As <IClaimsManager>() .InstancePerLifetimeScope(); builder.RegisterType <UserManager>() .As <IUserManager>() .InstancePerLifetimeScope(); builder.RegisterType <RequestManager>() .As <IRequestManager>() .InstancePerLifetimeScope(); builder.RegisterType <RoleRepository>() .As <IRoleRepository>() .InstancePerLifetimeScope(); }
public void TestCase1() { AutofacHelper.InitAutofacContainer(); var fun = AutofacHelper.GetInstance <IFun>(); Assert.AreEqual("Fun1", fun.GetInstanceType()); }
public VehicleMakeViewModel(VehicleMakeService vehicleMakeService, IMapper m) { vms = vehicleMakeService; vehicleMake = AutofacHelper.GetInstance().GetContainer().Resolve <VehicleMakeModel>(); mapper = m; VehicleMakes = new ObservableCollection <VehicleMakeModel>(); GetVehicleMake(); CreateComand = new Command(() => { CreateCommandFunction(); }); DeleteComand = new Command(() => { DeleteCommandFunction(); }); UpdateCommand = new Command(() => { UpdateCommandFunction(); }); SelectedMakeCommand = new Command(() => { SeletedMakeCommandFunction(); }); SearchCommand = new Command(() => { SearchFunction(); }); }
protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); //autofac初始化 AutofacHelper.Init(); }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext"></param> public void OnActionExecuting(ActionExecutingContext filterContext) { ICheckSignBusiness checkSignBusiness = AutofacHelper.GetService <ICheckSignBusiness>(); //若为本地测试,则不需要校验 if (GlobalSwitch.RunModel == RunModel.LocalTest) { return; } //判断是否需要签名 List <string> attrList = FilterHelper.GetFilterList(filterContext); bool needSign = attrList.Contains(typeof(CheckSignAttribute).FullName) && !attrList.Contains(typeof(IgnoreSignAttribute).FullName); //不需要签名 if (!needSign) { return; } //需要签名 var checkSignRes = checkSignBusiness.IsSecurity(filterContext.HttpContext); if (!checkSignRes.Success) { filterContext.Result = new ContentResult() { Content = checkSignRes.ToJson() }; } }
/// <summary> /// The Test /// </summary> public static void Test() { //AutofacHelper.Register<ITest1, Test1>(); AutofacHelper.Register <ITest1, Test1, TestIinterceptor>(); var it1 = AutofacHelper.Resolve <ITest1>(); it1.TestMethod(); Console.WriteLine("--------"); var ss2 = it1.TestMethod2(1212); Console.WriteLine("--------"); var ss3 = it1.TestMethod3(1212, "fsafasfasfsaf"); Console.WriteLine("--------"); var ss4 = it1.TestMethod4(null); Console.WriteLine("--------"); var ss5 = it1.TestMethod4(new TestObj { MyProperty = 2132131, MyProperty2 = "afljlfajflsa" }); Console.WriteLine("--------"); Console.WriteLine(ss2); Console.WriteLine(ss3); Console.WriteLine(ss4); Console.WriteLine(ss5); }
public void TestCase2() { AutofacHelper.InitAutofacContainer("../../Ioc/Autofac.xml"); var fun = AutofacHelper.GetInstance <IFun>(); Assert.AreEqual("Fun2", fun.GetInstanceType()); }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext filterContext) { IOperator Operator = AutofacHelper.GetService <IOperator>(); IBusHelper BusHelper = AutofacHelper.GetService <IBusHelper>(); var request = filterContext.HttpContext.Request; try { //若为本地测试,则不需要登录 if (GlobalSwitch.RunModel == RunModel.LocalTest) { return; } //判断是否需要登录 List <string> attrList = FilterHelper.GetFilterList(filterContext); bool needLogin = attrList.Contains(typeof(CheckLoginAttribute).FullName) && !attrList.Contains(typeof(IgnoreLoginAttribute).FullName); //转到登录 if (needLogin && !Operator.Logged()) { RedirectToLogin(); } } catch (Exception ex) { BusHelper.HandleException(ex); RedirectToLogin(); } void RedirectToLogin() { if (request.IsAjaxRequest()) { filterContext.Result = new ContentResult { Content = new AjaxResult { Success = false, ErrorCode = 1, Msg = "未登录" }.ToJson(), ContentType = "application/json;charset=UTF-8" }; } else { UrlHelper urlHelper = new UrlHelper(filterContext); string loginUrl = urlHelper.Content("~/Home/Login"); string script = $@" <html> <script> top.location.href = '{loginUrl}'; </script> </html> "; filterContext.Result = new ContentResult { Content = script, ContentType = "text/html" }; } } }
static void Main(string[] args) { IDataAccess dal = AutofacHelper.CreateInstance <IDataAccess>(); var res = dal.GetData(); Console.WriteLine(res); Console.ReadKey(); }
public static string MapPath(this HttpContext httpContext, string virtualPath) { UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetScopeService <IActionContextAccessor>().ActionContext); virtualPath = urlHelper.Content(virtualPath); return($"{Path.Combine(new List<string> { GlobalSwitch.WebRootPath }.Concat(virtualPath.Split('/')).ToArray())}"); }
/// <summary> /// build回调 /// </summary> /// <param name="builder"></param> private static void buildCallback(ContainerBuilder builder) { builder.RegisterBuildCallback(container => { //初始化Autofac容器 AutofacHelper.Init(container); }); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutofacHelper.Bootstrapper(typeof(MvcApplication).Assembly); }
public static IApplicationBuilder UseAllowedOrigins(this IApplicationBuilder app) { //跨域设置 var config = AutofacHelper.Resolve <IConfiguration>(); var allowedOrigins = config.GetValue <string>("AllowedOrigins") ?? string.Empty; return(app.UseCors(builder => builder.WithOrigins(allowedOrigins.Split(',')).AllowAnyMethod().AllowAnyHeader().AllowCredentials())); }
public async Task TestMethod1() { var roleService = AutofacHelper.GetService <ISysRolesService>(); var dataList = await roleService.GetModelsAsync(new SysRolesRequestModel() { }); Assert.IsTrue(dataList.ToList().Count > 0); }
public App() { InitializeComponent(); using (var scope = AutofacHelper.GetInstance().GetContainer().BeginLifetimeScope()) { var vmv = scope.Resolve <VehicleMakeView>(); var navigationPage = new NavigationPage(vmv); MainPage = navigationPage; } }
void Application_Start(object sender, EventArgs e) { Logger.Init(); AutofacHelper.Inject(); // Code that runs on application startup AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext filterContext) { IPermissionManage PermissionManage = AutofacHelper.GetService <IPermissionManage>(); IUrlPermissionManage UrlPermissionManage = AutofacHelper.GetService <IUrlPermissionManage>(); //若为本地测试,则不需要校验 if (GlobalSwitch.RunModel == RunModel.LocalTest) { return; } AjaxResult res = new AjaxResult(); //判断是否需要校验 List <string> attrList = FilterHelper.GetFilterList(filterContext); bool needCheck = attrList.Contains(typeof(CheckAppIdPermissionAttribute).FullName) && !attrList.Contains(typeof(IgnoreAppIdPermissionAttribute).FullName); if (!needCheck) { return; } var allRequestParams = HttpHelper.GetAllRequestParams(filterContext.HttpContext); if (!allRequestParams.ContainsKey("appId")) { res.Success = false; res.Msg = "缺少appId参数!"; filterContext.Result = new ContentResult { Content = res.ToJson() }; } string appId = allRequestParams["appId"]?.ToString(); var allUrlPermissions = UrlPermissionManage.GetAllUrlPermissions(); string requestUrl = filterContext.HttpContext.Request.Path; var thePermission = allUrlPermissions.Where(x => requestUrl.Contains(x.Url.ToLower())).FirstOrDefault(); if (thePermission == null) { return; } string needPermission = thePermission.PermissionValue; bool hasPermission = PermissionManage.GetAppIdPermissionValues(appId).Any(x => x.ToLower() == needPermission.ToLower()); if (hasPermission) { return; } else { res.Success = false; res.Msg = "权限不足!访问失败!"; filterContext.Result = new ContentResult { Content = res.ToJson() }; } }
public Client() { Config = AutofacHelper.GetService <SystemConfig>(); Protocol = JTTProtocolExtension.GetProtocol <JTT809Protocol>(Config.JTTConfigFilePath, Config.JTTVersion); Protocol.Initialization(); Protocol.DefaultVersionFlag = Config.JTTVersionFlag; Protocol.Structures = Config.Structures; Protocol.InternalEntitysMappings = Config.InternalEntitysMappings; Protocol.DataMappings = Config.DataMappings; Filter = Protocol.GetFilter(); }
void Application_Start(object sender, EventArgs e) { AutofacHelper.Inject(); RegisterGlobalFilters(GlobalFilters.Filters); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
protected override void Load(ContainerBuilder builder) { var services = new ServiceCollection(); services.AddLogging(opt => { opt.SetMinimumLevel(LogLevel.Debug); opt.AddDebug(); }); Assembly[] assembliesToScan = new Assembly[] { AppFramework.Core.AppFrameworkCore.Assembly, //Framework Assembly Core.CarCatalogCore.Assembly, //Service Assembly AppFrameworkModels.Assembly, //Models Assembly Assembly.GetExecutingAssembly() }; var sqlLiteMemoryConnection = new SqliteConnection("DataSource=:memory:"); sqlLiteMemoryConnection.Open(); //services.AddDbContext<CarCatalogContext>(options => _ = services.AddDbContextFactory <CarCatalogContext>(options => { options.UseSqlite(sqlLiteMemoryConnection); //options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=CarCatalog2;Trusted_Connection=True;MultipleActiveResultSets=true"); options.EnableSensitiveDataLogging(true); }); builder.Populate(services); builder.RegisterModule(new RegisterAutofacModule() { Assemblies = assembliesToScan }); builder.RegisterAutoMapper(assembliesToScan); builder.RegisterMediatR(assembliesToScan); builder.RegisterType <CarCatalogContext>(); builder.RegisterGeneric(typeof(CarCatalogRepository <>)).As(typeof(IAsyncRepository <>)).InstancePerLifetimeScope() .PropertiesAutowired() .OnActivated(args => AutofacHelper.InjectProperties(args.Context, args.Instance, true)); //specific service/repository builder.RegisterType <CarService>().As <ICarService>(); builder.RegisterType <CarRepository>().As <ICarRepository>(); builder.RegisterAssemblyTypes(CarCatalogModels.Assembly).Where(t => t.IsClosedTypeOf(typeof(IValidator <>))).AsImplementedInterfaces(); builder.RegisterType <AutofacValidatorFactory>().As <IValidatorFactory>().SingleInstance(); builder.RegisterType <UnitOfWork>().As(typeof(IUnitOfWork)); }
GetDomainEventHandlersFor <T>(T domainEvent, params string[] names) where T : IDomainEvent { IList <IDomaineventHandler <T> > handlers = new List <IDomaineventHandler <T> >(); foreach (var item in names) { var handler = AutofacHelper.ResolverNamed <IDomaineventHandler <T> >(item); handlers.Add(handler); } return(handlers); }
public void StartJob() { try { var cusService = AutofacHelper.GetService <ICrm_CustomerService>(); var s = cusService.GetTheData("039ed57b565cc-6b8ea799-9345-4e1f-84e1-fb3feee192d9"); Console.WriteLine("任务执行中"); } catch (Exception ex) { } }
/// <summary> /// 获取绝对路径 /// </summary> /// <param name="virtualPath">虚拟路径</param> /// <returns></returns> public static string GetAbsolutePath(string virtualPath) { string path = virtualPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); if (path[0] == '~') { path = path.Remove(0, 2); } string rootPath = AutofacHelper.GetService <IHostingEnvironment>().WebRootPath; return(Path.Combine(rootPath, path)); }
protected void Application_Start() { //注册路由 AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); //Autofac初始化 AutofacHelper.Init(); //未处理异常 GlobalFilters.Filters.Add(new GlobalHandleErrorAttribute()); }
/// <summary> /// 获取Url /// </summary> /// <param name="virtualUrl">虚拟Url</param> /// <returns></returns> public static string GetUrl(string virtualUrl) { if (!virtualUrl.IsNullOrEmpty()) { UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetService <IActionContextAccessor>().ActionContext); return(urlHelper.Content(virtualUrl)); } else { return(null); } }
public static async Task RunSample() { using (var container = MicrosoftDependencyContainerHelper.CreateServiceCollection()) { var mediator = container.GetService <IMediator>(); await SendCommands(mediator); } using (var container = AutofacHelper.CreateAutofacContainer()) { var mediator = container.Resolve <IMediator>(); await SendCommands(mediator); } }
/// <summary> /// 注册 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder"></param> public static void RegisterHttpService <T>(ContainerBuilder builder) where T : class, IHttpApi { builder.RegisterHttpApi <T>().ConfigureHttpApiConfig(c => { var configAttr = typeof(T).GetCustomAttributes(typeof(HttpHostConfigAttribute), false); if (configAttr != null && configAttr.Length > 0) { var hostConfig = configAttr.First() as HttpHostConfigAttribute; var config = AutofacHelper.Resolve <IConfiguration>(); c.HttpHost = new Uri(config[hostConfig.Key]); } c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; }); }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="context">过滤器上下文</param> public async override Task OnActionExecuting(ActionExecutingContext context) { if (context.ContainsFilter <NoApiPermissionAttribute>()) { return; } IPermissionBusiness permissionBus = AutofacHelper.GetScopeService <IPermissionBusiness>(); var permissions = await permissionBus.GetUserPermissionValuesAsync(Operator.UserId); if (!permissions.Contains(_permissionValue)) { context.Result = Error("权限不足!"); } }
public static IServiceCollection RegisterJTTServer(this IServiceCollection services, SystemConfig config) { services.AddJTT(options => { options.ProtocolOptions = new SuperSocket.JTT.Server.Model.JTTProtocolOptions { Version = config.JTTVersion, JTTCustomAssemblyName = Assembly.GetExecutingAssembly().GetName().Name, ConfigFilePath = config.JTTConfigFilePath, Structures = config.Structures, DataMappings = config.DataMappings, InternalEntitysMappings = config.InternalEntitysMappings, }; options.ServerOptions = new SuperSocket.JTT.Server.Model.JTTServerOptions { Name = config.ServerName, IP = config.ServerIP, Port = config.ServerPort, BackLog = config.ServerBackLog, UseUdp = true, PackageHandler = PackageHandler.Handler, OnConnected = SessionHandler.OnConnected, OnClosed = SessionHandler.OnClosed, InProcSessionContainer = true, ConfigureServices = (context, services, protocol) => { }, ConfigureAppConfiguration = (hostCtx, configApp, protocol) => { } }; options.LoggingOptions = new SuperSocket.JTT.Server.Model.JTTLoggingOptions { AddConsole = true, AddDebug = true, Provider = AutofacHelper.GetService <ILoggerProvider>() }; }); return(services); }