Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Dependency resolver.

License

NotificationsYou must be signed in to change notification settings

usausa/Smart-Net-Resolver

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NuGet

What is this?

Smart.Resolver .NET is simplified resolver library, degradation version of Ninject.

  • ASP.NET Core / Generic Host support
  • Transient, Singleton, Container(child) and custom scope supported
  • Callback, Constant provider supported
  • Property injection supported (optional)
  • Custom initialize processor supported
  • Construct with parameter supported
  • Constraint supported (like keyed)
  • Missing handler supported (For automatic registration, open generic type, ...)
  • Customization-first implementation, but not too late (see benchmark)

Usage example

publicinterfaceIService{}publicsealedclassService:IService{}publicsealedclassController{privateIServiceService{get;}publicController(IServiceservice){Service=service;}}// Usagevarconfig=newResolverConfig();config.Bind<IService>().To<Service>().InSingletonScope();config.Bind<Controller>().ToSelf();varresolver=config.ToResolver();varcontroller=resolver.Get<Controller>();

NuGet

PackageNote
NuGet BadgeCore libyrary
NuGet BadgeMicrosoft.Extensions.DependencyInjection integration
NuGet BadgeConfiguration extension

Bindings

Supported binding syntax.

  • Bind
  • To
// Type IService to Service Type instanceconfig.Bind<IService>().To<Service>();
  • ToSelf
// Type Controller to Controller Type instanceconfig.Bind<Controller>().ToSelf();
  • ToMethod
// Type IScheduler to factory methodconfig.Bind<IScheduler>().ToMethod(x=>x.Get<ISchedulerFactory>().GetScheduler());
  • ToConstant
// Type Messenger to instanceconfig.Bind<Messenger>().ToConstant(Messenger.Default);
  • InTransientScope
  • InSingletonScope
  • InScope
  • Keyed
  • WithConstructorArgument
  • WithPropertyValue
  • WithMetadata

Scope

Supported scope.

Transient (default)

  • New instance created each time
  • Lifecycle is not managed by resolver
config.Bind<TransientObject>().ToSelf().InTransientScope();

or

config.Bind<TransientObject>().ToSelf();

Singleton

  • Single instance created and same instance returned
  • Lifecycle managed by resolver (IScopeStorage) and Dispose called when resolver disposed
config.Bind<SingletonObject>().ToSelf().InSingletonScope();

Container

  • Single instance created and same instance returned per child container
  • Lifecycle managed by child container and Dispose called when resolver disposed
config.Bind<ScopeObject>().ToSelf().InContainerScope();

Custom

  • You can create a custom scope
config.Bind<CustomeScopeObject>().ToSelf().InScope(newCustomeScope());

Attribute

Prepared by standard.

ResolveByAttribute

Key constraint for lookup binding.

publicsealedclassChild{}publicsealedclassParent{pulbicChild Child{get;}publicParent([ResolveBy("foo")]Childchild){Child=child;}}// Usagevarconfig=newResolverConfig();config.Bind<Child>().ToSelf().InSingletonScope().Keyed("foo");config.Bind<Child>().ToSelf().InSingletonScope().Keyed("bar");config.Bind<Parent>().ToSelf();varresolver=config.ToResolver();varparent=resolver.Get<Parent>();varfoo=resolver.Get<Child>("foo");varbar=resolver.Get<Child>("bar");Debug.Assert(parent.Child==foo);Debug.Assert(parent.Child!=bar);

InjectAttribute

Mark of property injection target or select constructor.

publicsealedclassHasPropertyObject{[Inject]publicTargetTarget{get;set;}}

Parameter

Set constructor argument or property value.

publicsealedclassSceduler{publicSceduler(ITimertimer,inttimeout){}}// Usageconfig.Bind<ITimer>().To<Timer>().InSingletonScope();config.Bind<Sceduler>().ToSelf().InSingletonScope().WithConstructorArgument("timeout",30);

Configuration

StandardResolver is constructed from sub-components. Change the sub-components in ResolverConfig, can be customized StandardResolver.

// Add custom processor to pipelinepublicsealedclassCustomInitializeProcessor:IProcessor{publicvoidInitialize(objectinstance){...}}config.UseProcessor<CustomInitializeProcessor>();
// Add custome scopepublicsealedclassCustomScope:IScope{privatestaticreadonlyThreadLocal<Dictionary<IBinding,object>>Cache=newThreadLocal<Dictionary<IBinding,object>>(()=>newDictionary<IBinding,object>());publicIScopeCopy(IComponentContainercomponents){returnthis;}publicFunc<IResolver,object>Create(IBindingbinding,Func<object>factory){return resolver=>{if(Cache.Value.TryGetValue(binding,outvarvalue)){returnvalue;}value=factory();Cache.Value[binding]=value;returnvalue;};}}config.Components.Add<CustomScopeStorage>();config.Bind<SimpleObject>().ToSelf().InScope(newCustomScope());

Integration

See the sample project for details.

ASP.NET Core 3.1

publicstaticclassProgram{publicstaticvoidMain(string[]args){CreateHostBuilder(args).Build().Run();}publicstaticIHostBuilderCreateHostBuilder(string[]args)=>Host.CreateDefaultBuilder(args).UseServiceProviderFactory(newSmartServiceProviderFactory()).ConfigureWebHostDefaults(webBuilder=>{webBuilder.UseStartup<Startup>();});}
publicsealedclassStartup{...publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();}publicvoidConfigureContainer(ResolverConfigconfig){// Add component}...}

Generic Host

publicstaticclassProgram{publicstaticasyncTaskMain(string[]args){awaitnewHostBuilder().UseServiceProviderFactory(newSmartServiceProviderFactory()).ConfigureContainer<ResolverConfig>(ConfigureContainer).RunAsync();}privatestaticvoidConfigureContainer(ResolverConfigconfig){// Add component}}

Other

Ohter topics.

IInitializable

If the class implements Initializable, Initialized called after construct.

protectedclassInitializableObject:IInitializable{publicboolInitialized{get;privateset;}publicvoidInitialize(){Initialized=true;}}// Usageconfig.Bind<InitializableObject>().ToSelf().InSingletonScope();varobj=resolver.Get<InitializableObject>();Debug.Assert(obj.Initialized);

Constraint

If custom constraints want is as follows:

// Create IConstraint implementpublicsealedclassHasMetadataConstraint:IConstraint{publicstringKey{get;}publicHasMetadataConstraint(stringkey){Key=key;}publicboolMatch(IBindingMetadatametadata){returnmetadata.Has(Key);}}// Create ConstraintAttribute derived classpublicsealedclassHasMetadataAttribute:ConstraintAttribute{publicstringKey{get;}publicHasMetadataAttribute(stringkey){Key=key;}publicoverrideIConstraintCreateConstraint(){returnnewHasMetadataConstraint(Key);}}// UsagepublicsealedclassParent{pulbicChild Child{get;}publicParent([HasMetadata("hoge")]Childchild){Child=child;}}config.Bind<Child>().ToSelf().InSingletonScope();config.Bind<Child>().ToSelf().InSingletonScope().WithMetadata("hoge",null);config.Bind<Parent>().ToSelf();

Benchmark (for reference purpose only)

BenchmarkDotNet v0.13.12, Windows 11 (10.0.22631.3958/23H2/2023Update/SunValley3)AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores.NET SDK 8.0.400  [Host]    : .NET 8.0.8 (8.0.824.36612), X64 RyuJIT AVX2  MediumRun : .NET 8.0.8 (8.0.824.36612), X64 RyuJIT AVX2Job=MediumRun  Jit=RyuJit  Platform=X64  Runtime=.NET 8.0  IterationCount=15  LaunchCount=2  WarmupCount=10
MethodMeanErrorStdDevMinMaxP90Gen0Allocated
Singleton2.258 ns0.0221 ns0.0331 ns2.223 ns2.328 ns2.313 ns--
Transient11.712 ns0.8301 ns1.2424 ns10.154 ns13.742 ns13.439 ns0.001424 B
Combined22.017 ns0.2220 ns0.3322 ns21.503 ns22.911 ns22.385 ns0.001424 B
Complex36.063 ns0.5290 ns0.7754 ns35.258 ns38.750 ns36.957 ns0.0081136 B
Generics4.113 ns0.0513 ns0.0720 ns3.995 ns4.249 ns4.194 ns0.001424 B
MultipleSingleton2.074 ns0.0226 ns0.0324 ns2.033 ns2.143 ns2.116 ns--
MultipleTransient91.725 ns0.8332 ns1.2471 ns89.852 ns94.266 ns93.480 ns0.0110184 B
AspNet101.012 ns0.8376 ns1.1465 ns99.009 ns103.599 ns102.215 ns0.0153256 B

Unsupported

  • AOP( ゚д゚)、ペッ
  • Method Injection (I don't need but it is possible to cope)
  • Circular reference detection (Your design bug)

[8]ページ先頭

©2009-2025 Movatter.jp