如何将服务名称添加到数据库

How to add service names to database

我有接口

public interface ISocialService
    {
        //...
    }

和class

public class RedditService : ISocialService
{

        private readonly DbContext _context;

        public RedditService(DbContext context)
        {
            _context = context;
        }
}

我还有一些实现 IRedditService 的其他服务。

这是我的 DbContext:

public class DbContext : IdentityDbContext
    {

        private readonly IEnumerable<ISocialService> _socialServices;
        public DbContext(DbContextOptions<CrastinatorContext> options, IEnumerable<ISocialService> socialServices) : base(options)
        {
            _socialServices = socialServices;
        }
        //...

        public DbSet<SiteName> SiteNames { get; set; }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            //...
            foreach (var site in socialservices)
            {
                builder.Entity<SiteName>()
                    .HasData(new { Name = site.GetType().Name });

            }

        }

但我不能这样做,因为 SocialServices 已将 dbcontext 注入到构造函数中,所以我无法将 socialservices 注入到 dbcontext。 (循环依赖) 之所以要在db中添加方法名:

我想从特定服务向用户发送数据。 例如,如果用户有 RedditService 首选项,则从 RedditService 向他发送数据,如果用户有 ServiceA、ServiceB, 然后从ServiceA和ServiceB等发送数据。

所以我想将这些服务名称存储在数据库中。 然后在控制器中我会检查用户偏好:if(user has serviceA) then send data from serviceA.

还有其他方法吗?

TLDR:我想将 MethodNames 添加到 SiteNames table 但我不知道应该在哪里做。

你可以通过反射找到ISocialService的所有实现,这样就不需要将它们注入到DbContext中。这是一个示例。

public interface ISocialService { }
public class FacebookService : ISocialService { }
public class RedditService : ISocialService { }

public class Program
{
    static void Main(string[] args)
    {
        var socialServices = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => typeof(ISocialService).IsAssignableFrom(p) && p.IsClass);

        foreach (var t in socialServices)
        {
            Console.WriteLine(t.Name);
        }
    }
}

不过,我建议稍微重新设计一下应用程序。否则,每次添加 ISocialService 的新实现或重命名任何现有实现时,都需要重新为数据库设置种子。我会谨慎对待这样的联轴器。