I have a domain service that has ISession as a dependency in the Ctor.
public JobCreator(IMapper mapper, ISession session)
{
_mapper = mapper;
_session = session;
}
The service is registered as Singleton
container.Register<IKindergardenCreator, KindergardenCreator>(Lifestyle.Singleton);
The ISession however is registered as scoped, since the session should be reopened more than once.
container.Register<ISession>(() => container.GetInstance<ISessionFactory>().OpenSession(),
Lifestyle.Scoped);
When I run the app I get a "Lifestyle mismatch" because of this configuration. What is the right way to configure a singleton service with non singleton service?
What is the right way to configure a singleton service with non singleton service?
The exception information refers to the following documentation
The documentation about lifestyle mismatches explains how to fix violations:
- Change the lifestyle of the component to a lifestyle that is as short or shorter than that of the dependency.
- Change the lifestyle of the dependency to a lifestyle as long or longer than that of the component.
- Instead of injecting the dependency, inject a factory for the creation of that dependency and call that factory every time an instance is required.
Since you can't increase the lifestyle of the ISession dependency, you should either lower the lifestyle of your consuming component (the KindergardenCreator
) or inject a factory for ISession
instead.
You can lower the lifestyle of your component as follows:
container.Register<IKindergardenCreator, KindergardenCreator>(Lifestyle.Scoped);
You can also change the ISession
dependency to Func<ISession>
and register this as a factory as follows:
container.RegisterSingleton<Func<ISession>>(container.GetInstance<ISession>);