I would like to implement service with explicit interface implementation. I don't want to have public methods in service, only possible way to create instance is trough interface.
I am not sure what is best way to call method of same class if method is explicit implementation of interface method.
You can see in my code that I am using "AsIArchiveService" property.
I have public interface in class library:
using Common.Entities;
using System.Threading.Tasks;
namespace Common.Services
{
public interface IArchiveService
{
Task<ArchiveConfiguration> GetConfiguration();
Task<bool> Update(ArchiveConfiguration machine);
}
}
Serivice class in main project:
using Common.Configurations;
using Common.Entities;
using Common.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RemoteManager.EntityFramework;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Manager.Services
{
internal class ArchiveService : IArchiveService
{
private readonly IOptions<ApplicationConfiguration> applicationConfiguration;
private readonly ILogger<ArchiveService> logger;
private readonly ManagerContext context;
IArchiveService AsIArchiveService
{
get { return this; }
}
internal ArchiveService(ManagerContext context, IOptions<ApplicationConfiguration> applicationConfiguration, ILogger<ArchiveService> logger)
{
this.applicationConfiguration = applicationConfiguration;
this.logger = logger;
this.context = context;
}
async Task<ArchiveConfiguration> IArchiveService.GetConfiguration()
{
try
{
logger.LogInformation($"Start {nameof(ArchiveService)}:{nameof(AsIArchiveService.GetConfiguration)}");
if (this.context.ArchiveConfiguration.Count() == 0)
{
var res = this.context.ArchiveConfiguration.Add(new ArchiveConfiguration() { isArchive = true, maxDataSetCount = 20, path = Path.Combine("C:/", "TestArchive") });
this.context.SaveChanges();
}
var result = this.context.ArchiveConfiguration.First();
return await Task.FromResult(result);
}
catch
{
logger.LogError($"Error {nameof(ArchiveService)}:{nameof(AsIArchiveService.GetConfiguration)}");
throw;
}
}
async Task<bool> IArchiveService.Update(ArchiveConfiguration archive)
{
try
{
logger.LogInformation($"Start {nameof(ArchiveService)}:{nameof(AsIArchiveService.Update)}");
this.context.Entry(archive).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
this.context.SaveChanges();
return await Task.FromResult(true);
}
catch
{
logger.LogError($"Error {nameof(ArchiveService)}:{nameof(AsIArchiveService.Update)}");
throw;
}
}
}
}
IArchiveService service = new ArchiveService();
gives you anIArchiveService
. I'm not sure why you'd need the property to return itself as its interface? \$\endgroup\$