Share via


How to: Register and Use Services

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies.
This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

This topic describes how to register and use services in a Web client application. For information about services, see Services.

Prerequisites

This topic assumes that you have an existing Web client solution. For information about how to create a Web client solution, see How to: Create a Web Client Solution.

Steps

The following procedure describes how to register module services in your module initialization class.

To register module services in your module initializer

  1. In the module initialization class of your module, locate the AddModuleServices method, as shown in the following code.

    protected virtual void AddModuleServices(IServiceCollection moduleServices)
    {
      // TODO: add a service that will be visible to this module
    }
    

    The moduleServices parameter is the service collection for the module's composition container. If you add services to this composition container, the services will be available only to the module.

  2. In the method body, use either the Add or AddNew method to register the services:

    • Add. You use this method to register an existing instance (it has already been created) of a service. The ObjectBuilder strategies are executed on the instance and the service is added to the collection.

      moduleServices.Add(myService);
      
    • AddNew. You use this method to have ObjectBuilder create an instance of the service, run its strategies, and register it in the services collection.

      moduleServices.AddNew(typeof(MyService));
      
      // using generics:
      moduleServices.AddNew<MyService>();
      

Both the Add and AddNew methods provide overloads that allow you to specify the type that is used to register the service. This is the type developers use to obtain a reference to the service, as shown in the following code.

// AddNew method
moduleServices.AddNew(typeof(MyService), typeof(IMyService));
// AddNew method using generics:
moduleServices.AddNew<MyService, IMyService>();

// Add method
moduleServices.Add(typeof(IMyService), myService);
// Add method using generics:
moduleServices.Add<IMyService>(myService);

Note

Module services override global services. This means that if a global service is registered with a particular type, and a module service is registered with the same type in a module’s composition container, ObjectBuilder will inject the service registered at the module level when injecting dependencies in objects within that module.

The following procedure describes how to register global services in your module initialization class.

To register global services in your module initialization class

  1. In the module initialization class of your module, locate the AddGlobalServices method, as shown in the following code.

    protected virtual void AddGlobalServices(IServiceCollection services)
    {            
      // TODO: add a service that will be visible to any module
    }
    

    The services parameter is the services collection of the root composition container. If you register a service with this collection, it will be accessible from all modules in the application.

  2. In the method body, register services using the Add method or the AddNew method, as shown in the following sample code.

    protected virtual void AddGlobalServices(IServiceCollection services)
    {
      services.AddNew<EnterpriseLibraryAuthorizationService, IAuthorizationService>();
      services.AddNew<PermissionsCatalog, IPermissionsCatalog>();
      services.AddNew<RolesCatalog, IRolesCatalog>();
      services.AddNew<SiteMapBuilderService, ISiteMapBuilderService>();
    }
    

    Note

    You can also extend the WebClientApplication class and override the AddRequiredServices method to register global services. Use this option to add global infrastructure services or to replace initialization services, such as the ModuleLoaderService service.

The following procedure describes how to register services through configuration.

To register services through configuration

  1. Create a services element in the Web.config file of a module, inside the module element.

    <module name="Module1" assemblyName="Module1" virtualPath="~/Module1">
      <services>
    
      </services>
      <dependencies>
        <dependency module="Shell" />
      </dependencies>
    </module> 
    
  2. Add a service element inside the services element of the module for each service that you want to register. A service element must have the following attributes:

    • registerAs. Indicates the type that developers will use to obtain a reference to the service.
    • type. Indicates the type of the service to register.
    • scope. Indicates the scope of the service.****Valid values for the attribute are “Module” (for module services) and “Global” (for global services).

    The following XML is an example of the service element (in this example, the service is registered as a global service).

    <services>
      <service registerAs="WebClientApplication1.Module1.Services.IService1, Module1" type="WebClientApplication1.Module1.Services.Service1, Module1" scope="Global"/>
    </services>
    

You can obtain references to services declaratively or programmatically. The following procedure describes how to declaratively obtain references to services.

To declaratively obtain references to services

  • Use the ServiceDependency attribute to cause ObjectBuilder to inject a valid service instance when it creates the object. You can use the attribute in a public property, in an injection constructor parameter, or in an injection method parameter.

    If ObjectBuilder does not find the required service in the Services collection of the current composition container, the service is retrieved from the Services collection of the parent composition container. If the service is not found, ObjectBuilder throws a ServiceMissingException exception.

    The following code shows how to use the ServiceDependency attribute in a constructor.

    public ElectronicFundsTransferController
      (
        [ServiceDependency] IAccountServiceAgent accountServiceAgent
      )
    {
      _accountServiceAgent = accountServiceAgent;
    }
    

    If you have more than one constructor in your class, add the InjectionConstructor attribute to the constructor that you want ObjectBuilder to invoke when it creates an instance of your class.

    [InjectionConstructor]
    public ElectronicFundsTransferController
      (
        [ServiceDependency] IAccountServiceAgent accountServiceAgent
      )
    {
      _accountServiceAgent = accountServiceAgent;
    }
    

    The following code shows how to use the ServiceDependency attribute in a public property.

    private IAccountServiceAgent _accountServiceAgent;
    
    [ServiceDependency]
    public IAccountServiceAgent AccountServiceAgent
    {
      set { _accountServiceAgent = value; }
    }
    

    Note

    Notes:
    You can specify the named parameter Required=false in the ServiceDependency attribute to indicate that the dependency is optional. If the service is not found, ObjectBuilder returns a null reference instead of throwing a ServiceMissingException exception.
    If you require a specific concrete type, you can use the Type named parameter in the ServiceDependency attribute to specify the concrete type to be injected.

The following procedure describes how to programmatically obtain references to services.

To programmatically obtain references to services

  • Call the Get method of the Services collection of a composition container to programmatically get a reference to a service.

    MyService service = container.Services.Get(typeof(MyService));
    
    // using generics:
    MyService service = container.Services.Get<MyService>();
    

    The Get method retrieves the service from the Services collection. If ObjectBuilder does not find the required service in the Services collection of the current composition container, the service is retrieved from the Services collection of the parent composition container. If the service is not found, ObjectBuilder returns a null reference.

    Alternatively, you can use an overload of the Get method that declares an additional Boolean parameter named ensureExists. If you set this parameter to true, ObjectBuilder throws a ServiceMissingException exception if the service is not found. The following code demonstrates how to use the Get method with the ensureExists parameter set to true.

    public override void Load(ICompositionContainer moduleContainer)
    {
      base.Load(moduleContainer);
    
      RegisterSiteMapInformation(moduleContainer.Services.Get<ISiteMapBuilderService>(true));
      RegisterRequiredPermissions(moduleContainer.Services.Get<IPermissionsCatalog>(true));
    }