コード例 #1
0
        /// <summary>
        /// Use this method to pass your custom pre-configured container to the `IHostBuilder.UseServiceProviderFactory` in "Program.cs"
        /// </summary>
        public static IContainer CreateMyPreConfiguredContainer() =>
        // This is an example configuration,
        // for possible options check the https://github.com/dadhi/DryIoc/blob/master/docs/DryIoc.Docs/RulesAndDefaultConventions.md
        new Container(rules =>

                      // Configures property injection for Controllers, ensure that you've added `AddControllersAsServices` in `ConfigureServices`
                      rules.With(propertiesAndFields: request =>
                                 request.ServiceType.Name.EndsWith("Controller") ? PropertiesAndFields.Properties()(request) : null)
                      );
コード例 #2
0
        public void Can_specify_all_to_throw_if_Any_property_is_unresolved()
        {
            var container = new Container();

            container.Register <ClientWithServiceAndStringProperty>(made: PropertiesAndFields.All(ifUnresolved: IfUnresolved.Throw));

            Assert.Throws <ContainerException>(() =>
                                               container.Resolve <ClientWithServiceAndStringProperty>());
        }
コード例 #3
0
        public void Indexer_properties_should_be_ignored_by_All_properties_discovery()
        {
            var container = new Container();

            container.Register <FooWithIndexer>(made:
                                                PropertiesAndFields.All(ifUnresolved: IfUnresolved.Throw));

            Assert.DoesNotThrow(() =>
                                container.Resolve <FooWithIndexer>());
        }
コード例 #4
0
        public void Test()
        {
            var container = new Container();

            container.Register <FooWithIndexer>(made: PropertiesAndFields.All(ifUnresolved: IfUnresolved.Throw));

            Assert.DoesNotThrow(() =>
                                container.Resolve <FooWithIndexer>()
                                );
        }
コード例 #5
0
        /// <summary>Registers controllers types in container with InWebRequest reuse.</summary>
        /// <param name="container">Container to register controllers to.</param>
        /// <param name="controllerAssemblies">(optional) Uses <see cref="BuildManager.GetReferencedAssemblies"/> by default.</param>
        public static void RegisterMvcControllers(this IContainer container, IEnumerable <Assembly> controllerAssemblies = null)
        {
            controllerAssemblies = controllerAssemblies ?? GetReferencedAssemblies();
            container.RegisterMany(controllerAssemblies, type => type.IsAssignableTo(typeof(IController)),
                                   Reuse.InWebRequest, PropertiesAndFields.All(false, false, false, withInfo: (m, r) =>
            {
                if (m.DeclaringType != typeof(Controller) && m.DeclaringType != typeof(ControllerBase))
                {
                    return(PropertyOrFieldServiceInfo.Of(m).WithDetails(
                               ServiceDetails.Of(ifUnresolved: IfUnresolved.ReturnDefault), r));
                }

                return(null);
            }));
        }
コード例 #6
0
        public static PropertiesAndFieldsSelector AllPropertiesWithImportAttribute()
        {
            PropertyOrFieldServiceInfo info(MemberInfo m, Request r) => PropertyOrFieldServiceInfo.Of(m).WithDetails(ServiceDetails.Of(ifUnresolved: IfUnresolved.Throw));

            return(req =>
            {
                var properties = req.ImplementationType.GetMembers(_ => _.DeclaredProperties, includeBase: true)
                                 .Match(
                    p => CustomAttributeExtensions.GetCustomAttribute <ImportAttribute>((MemberInfo)p) != null &&
                    PropertiesAndFields.IsInjectable((PropertyInfo)p, withNonPublic: true, withPrimitive: false),
                    p => info(p, req));

                return properties;
            });
        }
コード例 #7
0
        public void Can_resolve_only_properties()
        {
            var container = new Container();

            container.Register <IService, Service>();
            container.Register <IService, AnotherService>(serviceKey: "another");

            container.RegisterMany <ClientWithPropsAndFields>(
                made: PropertiesAndFields.All(withFields: false).OverrideWith(PropertiesAndFields.Of.Name("PInternal", serviceKey: "another")));

            var client = container.Resolve <ClientWithPropsAndFields>();

            Assert.That(client.P, Is.InstanceOf <Service>());
            Assert.That(client.PWithBackingInternalProperty, Is.InstanceOf <AnotherService>());
            Assert.That(client.F, Is.Null);
            Assert.That(client.PWithBackingField, Is.Null);
            Assert.That(client.PNonResolvable, Is.Null);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: nodyang/DryIoc
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(new WebApplicationOptions
            {
                Args            = args,
                ContentRootPath = Directory.GetCurrentDirectory(),
                // etc.
            });


            // ## Dependency Injection stuff
            // -----------------------------------------------------------
            var container = new Container(rules =>
                                          // optional: Enables property injection for Controllers
                                          rules.With(propertiesAndFields: request => request.ServiceType.Name.EndsWith("Controller")
                    ? PropertiesAndFields.Properties()(request)
                    : null));

            container.RegisterMyBusinessLogic();

            // Here it goes the integration with the existing DryIoc container
            var diFactory = new DryIocServiceProviderFactory(container, ExampleOfCustomRegisterDescriptor);

            builder.Host.UseServiceProviderFactory(diFactory);

            builder.Services
            .AddMvc(options => options.EnableEndpointRouting = false)
            .AddControllersAsServices();

            // other things...
            builder.Logging.ClearProviders();
            builder.Logging.AddConsole();
            //-----------------------------------------------------------


            var app = builder.Build();

            app.UseMvc();
            app.UseHttpsRedirection();
            app.UseAuthorization();

            app.Run();
        }
コード例 #9
0
ファイル: Startup.cs プロジェクト: zhangzihan/DryIoc
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services
            .AddMvc()

            // Enables controllers to be resolved by DryIoc, OTHERWISE resolved by infrastructure
            .AddControllersAsServices();

            return(new Container(rules => rules.With(

                                     // optional: Enables property injection for Controllers
                                     // NOTE: it will be overriden by MEF convention (ImportAttribute) with the `WithMef()` line below .
                                     propertiesAndFields: request => request.ServiceType.Name.EndsWith("Controller")
                    ? PropertiesAndFields.Properties()(request)
                    : null))

                   .WithMef() // optional: support for MEF service discovery

                   .WithDependencyInjectionAdapter(services,
                                                   // optional: get original DryIoc.ContainerException if specified type is not resolved,
                                                   // and prevent fallback to default resolution by infrastructure
                                                   throwIfUnresolved: type => type.Name.EndsWith("Controller"),

                                                   // optional: You may Log or Customize the infrastructure components registrations
                                                   registerDescriptor: (registrator, descriptor) =>
            {
#if DEBUG
                if (descriptor.ServiceType == typeof(ILoggerFactory))
                {
                    Console.WriteLine($"Logger factory is registered as instance: {descriptor.ImplementationInstance != null}");
                }
#endif
                return false;         // fallback to default registration logic
            })

                   // Your registrations are defined in CompositionRoot class
                   .ConfigureServiceProvider <CompositionRoot>());
        }
コード例 #10
0
ファイル: DryIocWebApi.cs プロジェクト: OpuZm/NHRTest
        /// <summary>Registers controllers found in provided assemblies with <see cref="Reuse.InWebRequest"/>.</summary>
        /// <param name="container">Container.</param>
        /// <param name="config">Http configuration.</param>
        /// <param name="assemblies">Assemblies to look for controllers.</param>
        public static void RegisterWebApiControllers(this IContainer container, HttpConfiguration config,
                                                     IEnumerable <Assembly> assemblies = null)
        {
            var assembliesResolver = assemblies == null
                 ? config.Services.GetAssembliesResolver()
                 : new GivenAssembliesResolver(assemblies.ToList());

            var controllerTypeResolver = config.Services.GetHttpControllerTypeResolver();
            var controllerTypes        = controllerTypeResolver.GetControllerTypes(assembliesResolver);

            container.RegisterMany(controllerTypes, Reuse.InWebRequest,
                                   PropertiesAndFields.All(false, false, false, withInfo: (m, r) =>
            {
                if (m.DeclaringType != typeof(ApiController))
                {
                    return(PropertyOrFieldServiceInfo.Of(m).WithDetails(
                               ServiceDetails.Of(ifUnresolved: IfUnresolved.Throw), r));
                }

                return(null);
            }),
                                   nonPublicServiceTypes: true);
        }
コード例 #11
0
ファイル: Startup.cs プロジェクト: stantoxt/DryIoc
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services
            .AddLogging(logging => logging.AddConsole())
            .AddMvc()
            // Enables controllers to be resolved by DryIoc, OTHERWISE resolved by infrastructure
            .AddControllersAsServices();

            // Container in V4 is directly implementing `IServiceProvider`, so it is fine to return it.
            return(new Container(rules =>
                                 // optional: Enables property injection for Controllers
                                 // In current setup `WithMef` it will be overriden by properties marked with `ImportAttribute`
                                 rules.With(propertiesAndFields: request => request.ServiceType.Name.EndsWith("Controller")
                        ? PropertiesAndFields.Properties()(request)
                        : null)
                                 )
                   // optional: support for MEF Exported services
                   .WithMef()
                   .WithDependencyInjectionAdapter(services,
                                                   // optional: You may Log or Customize the infrastructure components registrations
                                                   MyCustomRegisterDescriptor)
                   // Your registrations are defined in CompositionRoot class
                   .WithCompositionRoot <MyCompositionRoot>());
        }
コード例 #12
0
 public static IContainer CreateConfiguredContainer() =>
 new Container(rules =>
               rules.With(propertiesAndFields: request =>
                          request.ServiceType.Name.EndsWith("Controller") ? PropertiesAndFields.Properties()(request) : null)
               );