Autofac Series II, Resolution Service

First, the resolution service

After registering your components and expose the appropriate service, the service can be resolved by creating a container or its child life cycle, let us use the Resolve () method to achieve:

var builder = new ContainerBuilder();
builder.RegisterType<MyComponent>().As<IService>();
var container = builder.Build();

using(var scope = container.BeginLifetimeScope())
{
  var service = scope.Resolve<IService>();
}

We should note that the example is from the resolution service lifecycle rather than directly from the container, of course, you should also do the same.

    Maybe sometimes it can be resolved from the root container components in our application, but doing so may lead to memory leaks. You always recommended to resolve the component from the life cycle. To ensure that the service instance is properly released and garbage collection.

When resolution services, Autofac automatic link from the service on the entire chain of dependencies required for different levels and resolve all dependencies to complete building service, if you have a cycle of dependence improper handling or lack of mandatory dependency, you will get a DependencyResolutionException.

If you are not sure whether a service is registered, you can attempt to resolve by ResolveOptional () or TryResolve ():

// If IService is registered, it will be resolved; if
// it isn't registered, the return value will be null.
var service = scope.ResolveOptional<IService>();

// If IProvider is registered, the provider variable
// will hold the value; otherwise you can take some
// other action.
IProvider provider = null;
if(scope.TryResolve<IProvider>(out provider))
{
  // Do something with the resolved provider value.
}

ResolveOptional () and TryResolve () is essentially just to ensure that a particular service has been successfully registered. If the component is already registered will be successfully resolved. If the resolution itself fails (such as certain required dependencies not registered), you will still get DependencyResolutionException. If you are unsure whether the service will be successful to resolve itself and the need for different actions when parsing succeeds or fails, the Resolve () parcel try..cath block in.

Guess you like

Origin www.cnblogs.com/mantishell/p/12203165.html