Ejemplo n.º 1
0
 public HomeController(ILogger <HomeController> logger, IComponentContext componentContext)
 {
     _logger           = logger;
     _componentContext = componentContext;
     _serviceA         = _componentContext.ResolveNamed <IServiceA>("ServiceA");
     _serviceUpdate    = _componentContext.ResolveNamed <IServiceA>("ServiceUpdate");
 }
        private static TService GetDecoratedService <TService>(IComponentContext c, string serviceName, string decoratorName)
        {
            var service   = c.ResolveNamed <TService>(serviceName);
            var decorator = c.ResolveNamed <TService>(decoratorName, TypedParameter.From(service));

            return(decorator);
        }
        public static bool TryTransform(IComponentContext ctx, IContext context, out ITransform transform)
        {
            transform = null;
            var success = true;

            if (ctx.IsRegisteredWithName <ITransform>(context.Operation.Method))
            {
                var t = ctx.ResolveNamed <ITransform>(context.Operation.Method, new PositionalParameter(0, context));

                foreach (var warning in t.Warnings())
                {
                    context.Warn(warning);
                }

                if (t.Errors().Any())
                {
                    foreach (var error in t.Errors())
                    {
                        context.Error(error);
                    }
                    success = false;
                }
                else
                {
                    transform = t;
                }
            }
            else
            {
                if (ctx.IsRegisteredWithName <ITransform>(context.Operation.Key))
                {
                    var t = ctx.ResolveNamed <ITransform>(context.Operation.Key, new PositionalParameter(0, context));

                    foreach (var warning in t.Warnings())
                    {
                        context.Warn(warning);
                    }

                    if (t.Errors().Any())
                    {
                        foreach (var error in t.Errors())
                        {
                            context.Error(error);
                        }
                        success = false;
                    }
                    else
                    {
                        transform = t;
                    }
                }
                else
                {
                    context.Error($"The {context.Operation.Method} method used in the {context.Field.Alias} field is not registered.");
                    success = false;
                }
            }
            return(success);
        }
Ejemplo n.º 4
0
 private IComponentContext _componentContext;//Autofac上下文
 //通过构造函数注入Service
 public HomeController(IPersonService personService, IComponentContext componentContext)
 {
     _personService    = personService;
     _componentContext = componentContext;
     //解释组件
     _wxPayService  = _componentContext.ResolveNamed <IPayService>(typeof(WxPayService).Name);
     _aliPayService = _componentContext.ResolveNamed <IPayService>(typeof(AliPayService).Name);
 }
Ejemplo n.º 5
0
        public async Task <ActionResult> Report(int urlId)
        {
            var modelByDate = await ComponentContext.ResolveNamed <IReport>(ReportType.ReportByLast7Days.ToString()).GetReport(urlId);

            var modelByCountry = await ComponentContext.ResolveNamed <IReport>(ReportType.ReportByCountry.ToString()).GetReport(urlId);

            var modelByBrowser = await ComponentContext.ResolveNamed <IReport>(ReportType.ReportByBrowser.ToString()).GetReport(urlId);

            var modelByPlatform = await ComponentContext.ResolveNamed <IReport>(ReportType.ReportByPlatforms.ToString()).GetReport(urlId);

            return(View(Tuple.Create(modelByDate, modelByCountry, modelByBrowser, modelByPlatform)));
        }
Ejemplo n.º 6
0
        public TestController(IComponentContext componentContext)
        {
            _componentContext = componentContext;
            //解释组件
            _wxPayService  = componentContext.ResolveNamed <IPayService>(typeof(WxPayService).Name);
            _aliPayService = componentContext.ResolveNamed <IPayService>(typeof(AliPayService).Name);

            //_wxPayService =AutofacContainer.Current.ResolveNamed<IPayService>(typeof(WxPayService).Name);
            //_aliPayService = AutofacContainer.Current.ResolveNamed<IPayService>(typeof(AliPayService).Name);

            //_wxPayService = AutofacContainer.Current.Resolve<IPayService>();
            //_aliPayService = AutofacContainer.Current.Resolve<IPayService>();
        }
Ejemplo n.º 7
0
 /// <inheritdoc />
 public virtual object GetService(Type serviceType, string contract = null)
 {
     try
     {
         return(string.IsNullOrEmpty(contract)
             ? _componentContext.Resolve(serviceType)
             : _componentContext.ResolveNamed(contract, serviceType));
     }
     catch (DependencyResolutionException)
     {
         return(null);
     }
 }
Ejemplo n.º 8
0
        // GET: Produc
        public ActionResult Index()
        {
            _productRepository = _icoContext.ResolveNamed <IProductRepository>(SourceName);

            var model = _productRepository.GetAll();

            if (model == null)
            {
                model = new List <Product>();
            }

            return(View(model));
        }
Ejemplo n.º 9
0
        public GojekBasePageView ResolvePage <T>(string name, NavigationParameters parameters = null)
            where T : GojekBasePageViewModel
        {
            var viewName = _namingConventions.GetViewName(name);

            if (!_componentContext.IsRegisteredWithName <GojekBasePageView>(viewName))
            {
                return(null);
            }

            var page = _componentContext.ResolveNamed <GojekBasePageView>(viewName);

            var viewModelName = _namingConventions.GetViewModelName(name);

            if (!_componentContext.IsRegisteredWithName <GojekBasePageViewModel>(viewModelName))
            {
                return(page);
            }
            var viewModel = _componentContext.ResolveNamed <GojekBasePageViewModel>(viewModelName);

            //assign current page navigator, dialoger
            viewModel.Navigator = _componentContext.Resolve <ICrossNavigator>();
            viewModel.Dialoger  = _componentContext.Resolve <ICrossDialogProvider>();

            #region title

            //set an toan truong hop quen dat title cho mot trang nao do trong resource
            if (!string.IsNullOrEmpty(viewModel.Title))
            {
                viewModel.Title = viewModel.Title;
            }

            NavigationPage.SetHasNavigationBar(page, viewModel.HasNavigationBar);
            NavigationPage.SetHasBackButton(page, viewModel.HasBackButton);
            NavigationPage.SetBackButtonTitle(page, viewModel.BackButtonTitle);

            #endregion

            //call init before page appearing only if parameter not null
            if (parameters != null)
            {
                page.OnInitializeView(parameters: parameters);
                viewModel.OnInitializeViewModel(parameters: parameters);
            }

            //extension bind viewmodel => view (page)
            page.BindCrossPageViewModel <T>(viewModel);
            return(page);
        }
Ejemplo n.º 10
0
        public void Run(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            if (args != null && args.Length > 1)
            {
                if (_container.IsRegisteredWithName <IPlugin>(args[0]))
                {
                    var plugin = _container.ResolveNamed <IPlugin>(args[0]);
                    plugin.Run(
                        args
                        .Select(a => a)
                        .Skip(1)
                        .ToArray()
                        );
                }
                else
                {
                    var msg = String.Format("Das Plugin {0} ist im DI-Container nicht (als IPlugin) registriert (Tippfehler?).",
                                            args[0]);
                    _logger.Log(LogLevel.Error, msg);
                }
            }
            else
            {
                _logger.Log(LogLevel.Warn,
                            args == null
                                                ? "Es wurden keine auswertbaren Parameter angegeben."
                                                : args.Length < 2
                                                        ? "Es wurden weniger als zwei Argumente angegeben (TaskRunner <Plugin> <Task>)."
                                                        : "");
            }
        }
Ejemplo n.º 11
0
        public AccountController(IComponentContext componentContext, IAccountService accountService)
        {
            bool isIdentityServer4 = Appsettings.IdentityServer4Enable;

            _tokenService   = componentContext.ResolveNamed <ITokenService>(isIdentityServer4 ? nameof(IdentityServer4Service) : nameof(JwtTokenService));
            _accountService = accountService;
        }
Ejemplo n.º 12
0
        private static ISessionFactory ConfigureSessionFactory(IComponentContext context)
        {
            var connectionStringProvider = context.Resolve <IConnectionStringSettings>();

            EntryMapping.CurrentSchema = connectionStringProvider.Schema;
            var databaseProvider = context.ResolveNamed <IDatabaseProvider>(connectionStringProvider.DatabaseProvider.ToLower());

            var databaseConfiguration = databaseProvider.GetDatabaseConfiguration(connectionStringProvider);
            var configuration         =
                Fluently
                .Configure()
                .Database(databaseConfiguration)
                .Mappings(m =>
            {
                m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly());

                //Scan extensions for nHibernate mappings
                var extension = context.Resolve <IEnumerable <ScriptedExtension> >();
                foreach (var assembly in extension.Select(provider => provider.SourceAssembly))
                {
                    m.FluentMappings.AddFromAssembly(assembly);
                }
            })
                .ProxyFactoryFactory(typeof(DefaultProxyFactoryFactory));

            return(configuration.BuildSessionFactory());
        }
Ejemplo n.º 13
0
        public virtual void Resolve(object sender, System.Reflection.FieldInfo field, IComponentContext context)
        {
            var fType = this.Type ?? field.FieldType;


            if (fType.IsAssignableTo <ILogger>())
            {
                var log = context.Resolve <ILoggerFactory>().CreateLogger(this.GetType().Name);
                field.SetValue(sender, log);
            }
            else
            {
                var named = this.Named;
                var keyed = this.Keyed;
                if (!string.IsNullOrWhiteSpace(named))
                {
                    var pInstance = context.ResolveNamed(named, fType);
                    field.SetValue(sender, pInstance);
                }
                else if (keyed != null)
                {
                    var pInstance = context.ResolveKeyed(keyed, fType);
                    field.SetValue(sender, pInstance);
                }
                else
                {
                    var pInstance = context.Resolve(fType);
                    field.SetValue(sender, pInstance);
                }
            }
        }
Ejemplo n.º 14
0
 protected override object DoGetInstance(Type serviceType,
                                         string key)
 {
     return(null == key
                ? _container.Resolve(serviceType)
                : _container.ResolveNamed(key, serviceType));
 }
Ejemplo n.º 15
0
        // this is confusing, refactor
        private static Process GetProcess(IComponentContext ctx, IEnumerable <Parameter> p, IEnumerable <IDependency> dependencies, string cfg = null)
        {
            var process = new Process(dependencies.ToArray());

            if (cfg != null)
            {
                process.Load(cfg);
                return(process);
            }

            switch (p.Count())
            {
            case 2:
                process.Load(
                    p.Named <string>("cfg"),
                    p.Named <Dictionary <string, string> >("parameters")
                    );
                return(process);

            case 1:
                process.Load(p.Named <string>("cfg"));
                return(process);

            default:
                if (ctx.IsRegisteredWithName <string>("cfg"))
                {
                    process.Load(ctx.ResolveNamed <string>("cfg"));
                    return(process);
                }

                return(process); // unloaded
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Resolve the appropriate <see cref="IStateObjectProvider"/> instance.
        /// </summary>
        /// <returns></returns>
        protected virtual IStateObjectProvider GetStateObjectProvider(IComponentContext context)
        {
            var store = context.ResolveOptional <IOptions <StateWebServiceOptions> >()?.Value?.Store ?? DefaultStoreName;
            var param = TypedParameter.From(context.ResolveNamed <IStateObjectDataStore>(store));

            return(context.Resolve <IStateObjectProvider>(param));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 属性注入
        /// note:PropertiesAutowired可以自动注入,但不好控制
        /// </summary>
        private void RegisterProperties(object obj, IComponentContext context)
        {
            var properties = obj.GetType().GetProperties().Where(p => p.PropertyType.IsInterface && p.CanWrite && p.IsDefined(typeof(DependencyPropertyAttribute), false)).ToList();

            //判断name的值
            properties.ForEach(p =>
            {
                var objAttrs = p.GetCustomAttributes(typeof(DependencyPropertyAttribute), false);
                if (objAttrs.Length > 0)
                {
                    var name = (objAttrs[0] as DependencyPropertyAttribute).Named;

                    if (string.IsNullOrEmpty(name))
                    {
                        var value = context.Resolve(p.PropertyType);
                        p.SetValue(obj, value, null);
                    }
                    else
                    {
                        var value = context.ResolveNamed(name, p.PropertyType);
                        p.SetValue(obj, value, null);
                    }
                }
            });
        }
Ejemplo n.º 18
0
        // this is confusing, refactor
        private static Process GetProcess(IComponentContext ctx, IEnumerable <Parameter> p, IEnumerable <IDependency> dependencies, string cfg = null)
        {
            var process = new Process(dependencies.ToArray());

            if (cfg != null)
            {
                process.Load(cfg);
                return(process);
            }

            switch (p.Count())
            {
            case 2:
                process.Load(
                    p.Named <string>("cfg"),
                    p.Named <Dictionary <string, string> >("parameters")
                    );
                return(process);

            case 1:
                process.Load(p.Named <string>("cfg"));
                return(process);

            default:
                if (ctx.IsRegisteredWithName <string>("cfg"))
                {
                    process.Load(ctx.ResolveNamed <string>("cfg"));
                    return(process);
                }

                throw new Exception("Configuration Container could not find the configuration!  Pass in or register a `cfg` string.");
            }
        }
Ejemplo n.º 19
0
        private static Option <ISyncService> CreateSyncService(IComponentContext context)
        {
            var config              = context.Resolve <GitConfig>();
            var signService         = context.Resolve <ISignService>();
            var passwordStore       = context.ResolveNamed <IDirectoryInfo>("PasswordStore");
            var notificationService = context.Resolve <INotificationService>();
            var strategies          = context.Resolve <GitSyncStrategies>();

            var factory = new SyncServiceFactory(config, passwordStore.FullName, signService, strategies);

            var syncService = factory.BuildSyncService();

            switch (factory.Status)
            {
            case SyncServiceStatus.GitLibraryNotFound:
                notificationService.ShowErrorWindow("The git2 DLL could not be found. Git support will be disabled.");
                break;

            case SyncServiceStatus.GitRepositoryNotFound:
                notificationService.ShowErrorWindow($"Failed to open the password store Git repository ({factory.Exception.GetType().Name}: {factory.Exception.Message}). Git support will be disabled.");
                break;
            }

            return(Option.FromNullable(syncService));
        }
Ejemplo n.º 20
0
        private static ISessionFactory ConfigureSessionFactory(IComponentContext context)
        {
            var connectionStringProvider = context.Resolve<IConnectionStringProvider>();
            EntryMapping.CurrentSchema = connectionStringProvider.Schema;
            var databaseProvider = context.ResolveNamed<IDatabaseProvider>(connectionStringProvider.DatabaseProvider.ToLower());

            var databaseConfiguration = databaseProvider.GetDatabaseConfiguration(connectionStringProvider);
            var configuration =
                Fluently
                    .Configure()
                    .Database(databaseConfiguration)
                    .Mappings(m =>
                                  {
                                      m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly());

                                      //Scan extensions for nHibernate mappings
                                      var extension = context.Resolve<IEnumerable<ScriptedExtension>>();
                                      foreach (var assembly in extension.Select(provider => provider.SourceAssembly))
                                      {
                                          m.FluentMappings.AddFromAssembly(assembly);
                                      }
                                  })
                    .ProxyFactoryFactory(typeof (DefaultProxyFactoryFactory));

            return configuration.BuildSessionFactory();
        }
Ejemplo n.º 21
0
        public AccountController(IComponentContext componentContext, IConfiguration configuration, IAccountService accountService)
        {
            bool isIdentityServer4 = configuration.GetSection("Service:IdentityServer4").Value?.ToBoolean() ?? false;

            _tokenService   = componentContext.ResolveNamed <ITokenService>(isIdentityServer4 ? typeof(IdentityServer4Service).Name : typeof(JwtTokenService).Name);
            _accountService = accountService;
        }
        public static bool TryValidator(IComponentContext ctx, IContext context, out IValidate validator)
        {
            validator = null;
            var result = true;

            if (ctx.IsRegisteredWithName <IValidate>(context.Operation.Method))
            {
                var v = ctx.ResolveNamed <IValidate>(context.Operation.Method, new PositionalParameter(0, context));

                foreach (var warning in v.Warnings())
                {
                    context.Warn(warning);
                }

                if (v.Errors().Any())
                {
                    foreach (var error in v.Errors())
                    {
                        context.Error(error);
                    }
                    result = false;
                }
                else
                {
                    validator = v;
                }
            }
            else
            {
                context.Error(string.Format("The {0} method used in the {1} field is not registered.", context.Operation.Method, context.Field.Alias));
                result = false;
            }
            return(result);
        }
Ejemplo n.º 23
0
 protected override object GetInstance(Type serviceType, string key)
 {
     return
         (string.IsNullOrWhiteSpace(key)
             ? _container.Resolve(serviceType)
             : _container.ResolveNamed(key, serviceType));
 }
Ejemplo n.º 24
0
        public void Run(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            System.Console.WriteLine("\nRegistered Components ({0}):",
                                     _container.ComponentRegistry.Registrations.Count());

            foreach (var entry in _container.ComponentRegistry.Registrations)
            {
                System.Console.WriteLine("   {0}", entry.ToString().Split(',')[0]);
                _logger.Log(LogLevel.Info, String.Format("Registered: {0}", entry.ToString().Split(',')[0]));
            }

            _logger.SetName("DbLogger");
            var hostName  = Dns.GetHostName();
            var ipAddress = Dns.GetHostEntry(hostName).AddressList[0].ToString();

            GlobalDiagnosticsContext.Set("ipAddress", ipAddress);
            GlobalDiagnosticsContext.Set("program", "TestHost");
            GlobalDiagnosticsContext.Set("level", "4");
            GlobalDiagnosticsContext.Set("messageId", "99999");

            _logger.Log(LogLevel.Info, "Test from NLog ;-)");
            _logger.SetName("$safeprojectname$");

            System.Console.WriteLine("\nFrom DataService:");
            _dataService.Hello();

            System.Console.WriteLine("\nRunning CheckDataPlugin:");
            var cr = _container.ResolveNamed <IPlugin>("CheckDataPlugin");

            cr.Run(args);

            try
            {
                System.Console.WriteLine("\nRunning ImportDataPlugin:");
                var ir = _container.ResolveNamed <IPlugin>("ImportDataPlugin");
                ir.Run(args);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
            }

            System.Console.Write("\nPress any key to continue . . . ");
            System.Console.ReadKey(true);
        }
 public override Boolean CanSupplyValue(ParameterInfo pi,
                                        IComponentContext context, out Func <Object> valueProvider)
 {
     valueProvider = null;
     if (pi.Name == "services" &&
         pi.ParameterType == typeof(Dictionary <String, IService>))
     {
         valueProvider = () =>
         {
             return(new Dictionary <string, IService> {
                 { "a", context.ResolveNamed <IService>("a") },
                 { "b", context.ResolveNamed <IService>("b") }
             });
         };
     }
     return(valueProvider != null);
 }
Ejemplo n.º 26
0
        protected virtual IHandlePoisonMessages BuildPoisonMessageHandler(IComponentContext c)
        {
            if (!this.enlist)
                return new NonTransactionalPoisonMessageHandler();

            return new PoisonMessageHandler(
                c.ResolveNamed<ISendToEndpoints>(PoisonEndpoint, new Parameter[0]), new Uri(this.poisonAddress), this.maxRetries,this.postHandlingAction);
        }
Ejemplo n.º 27
0
 protected override object DoGetInstance(Type serviceType, string key)
 {
     if (serviceType == null)
     {
         throw new ArgumentNullException("serviceType");
     }
     return(key != null?_container.ResolveNamed(key, serviceType) : _container.Resolve(serviceType));
 }
Ejemplo n.º 28
0
 public T Resolve <T>(string name = null)
 {
     if (name == null)
     {
         return(_ctx.Resolve <T>());
     }
     return(_ctx.ResolveNamed <T>(name));
 }
Ejemplo n.º 29
0
        public AccountController(IComponentContext componentContext, IAccountService accountService, IUserService userService)
        {
            bool isIdentityServer4 = Appsettings.IdentityServer4Enable;

            _tokenService   = componentContext.ResolveNamed <ITokenService>(isIdentityServer4 ? typeof(IdentityServer4Service).Name : typeof(JwtTokenService).Name);
            _accountService = accountService;
            _userService    = userService;
        }
Ejemplo n.º 30
0
        /// <inheritdoc />
        public IParser GetParser(CatalogType catalogType)
        {
            switch (catalogType)
            {
            case CatalogType.ReadManga:
                return(_context.ResolveNamed <IParser>("ReadManga"));

            case CatalogType.MintManga:
                return(_context.ResolveNamed <IParser>("MintManga"));

            case CatalogType.MangaFox:
                return(_context.ResolveNamed <IParser>("MangaFox"));

            default:
                throw new ArgumentException(nameof(catalogType));
            }
        }
Ejemplo n.º 31
0
 public object GetService(Type serviceType, string alias)
 {
     if (!_componentContext.IsRegisteredWithName(alias, serviceType))
     {
         return(null);
     }
     return(_componentContext.ResolveNamed(alias, serviceType));
 }
Ejemplo n.º 32
0
        public ICommand ParseCommand(string fullCommand)
        {
            var commandName     = fullCommand.Split()[0];
            var commandTypeInfo = this.FindCommand(commandName);
            var command         = context.ResolveNamed <ICommand>(commandName);

            return(command);
        }
Ejemplo n.º 33
0
        public static ITransform SwitchTransform(IComponentContext ctx, PipelineContext context) {
            context.Activity = PipelineActivity.Transform;
            switch (context.Transform.Method) {
                case "format": return new FormatTransform(context);
                case "left": return new LeftTransform(context);
                case "right": return new RightTransform(context);
                case "copy": return new CopyTransform(context);
                case "concat": return new ConcatTransform(context);
                case "fromxml": return new FromXmlTransform(context);
                case "fromsplit": return new FromSplitTransform(context);
                case "htmldecode": return new DecodeTransform(context);
                case "xmldecode": return new DecodeTransform(context);
                case "hashcode": return new HashcodeTransform(context);
                case "padleft": return new PadLeftTransform(context);
                case "padright": return new PadRightTransform(context);
                case "splitlength": return new SplitLengthTransform(context);
                case "timezone": return new TimeZoneOperation(context);
                case "trim": return new TrimTransform(context);
                case "trimstart": return new TrimStartTransform(context);
                case "trimend": return new TrimEndTransform(context);
                case "javascript": return new JintTransform(context);
                case "tostring": return new ToStringTransform(context);
                case "toupper": return new ToUpperTransform(context);
                case "tolower": return new ToLowerTransform(context);
                case "join": return new JoinTransform(context);
                case "map": return new MapTransform(context, ctx.ResolveNamed<IMapReader>(context.Process.Maps.First(m => m.Name == context.Transform.Map).Key));
                case "decompress": return new DecompressTransform(context);

                case "contains": return new ContainsValidater(context);
                case "is": return new IsValidator(context);

                default:
                    context.Warn("The {0} method is undefined.", context.Transform.Method);
                    return new NullTransformer(context);
            }
        }
 /// <summary>
 /// Resolves the named persistence reader using an <see cref="IComponentContext"/>.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="providerElement">The provider element.</param>
 /// <returns></returns>
 /// <remarks></remarks>
 private static object ResolveNamedPersistenceRepositoryProvider(IComponentContext context, PersistenceReaderElement providerElement)
 {
   return context.ResolveNamed(providerElement.InternalKey, providerElement.ToType());
 }
Ejemplo n.º 35
0
 public static Player ResolveDealer(IComponentContext componentContext)
 {
     return componentContext.ResolveNamed<Player>("dealer");
 }