I'm trying to inject my service as Singleton to my single-layered application, following the documentation .
My interface:
public interface ILObjectAppService: IApplicationService
{
DateTime GetTime();
string Login(string userName, string password, int frmNo);
void Disconnect();
}
The implementation:
[Dependency(ServiceLifetime.Singleton, TryRegister = true)]
[ExposeServices(typeof(ILObjectAppService))]
public class LObjectAppService : ApplicationService, ILObjectAppService
{
public static UnityObjects.UnityApplication _unityApp;
private readonly IStatusAppService _statusAppService;
public DateTime Time { get; set; }
public LObjectAppService(IStatusAppService statusAppService)
{
_statusAppService = statusAppService;
Time= DateTime.Now;
_unityApp= new UnityObjects.UnityApplication();
}
public DateTime GetTime()
{
return Time;
}
/ ... other methods
}
and this works just fine when I use it on the Presentation layer.
Index.cshtml.cs
public class IndexModel : AbpPageModel
{
private readonly ILObjectAppService _lObjectAppService;
public DateTime LObjectTime { get; set; }
public IndexModel(ILObjectAppService lObjectAppService)
{
_lObjectAppService = lObjectAppService;
}
public async Task OnGetAsync()
{
LObjectTime = _lObjectAppService.GetTime();
}
}
The problem is when I navigate to the swagger (https://localhost:44337/) and try to call GetTime
endpoint of the LObjectAppService, I get error RemoteServiceErrorInfo 500
.
The log file says:
Autofac.Core.Registration.ComponentNotRegisteredException: The requested service 'MyProject.Entegrator.Services.LObject.LObjectAppService' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
I Tried to register the context.Services.Singleton in the EntegratorModule.ConfigureServices() but that only crashed the application.
Am I registering my singleton service correct? What's the best practice here?
CodePudding user response:
It wouldn't be advisable to register an ApplicationService
as a singleton, as you'll end up with captive dependencies.
That being said, the error appears as though the DI container is trying to resolve the concrete type...Are you using conventional controller registration, or have you manually wired up a controller? If so, I'd suggest you've probably added a dependency on the concrete type LObjectAppService
rather than the interface ILObjectAppService
.
I believe you will need the [Dependency(ReplaceServices=true)]
enabled to replace the existing registration.