在 C# 中使用委托参数重构为泛型方法

问题描述

所以我有下面的方法,但在将它们转换为使用通用 dbcontext 时遇到了问题。这里有什么想法吗?

        public static async Task ExecuteScopeAsync<TDbContext>(this IServiceScopeFactory scopeFactory,Func<IServiceProvider,Task> action)
            where TDbContext : DbContext
        {
            using var scope = scopeFactory.CreateScope();
            var dbContext = scope.ServiceProvider.GetrequiredService<TDbContext>();

            try
            {
                //await dbContext.BeginTransactionAsync();

                await action(scope.ServiceProvider);

                //await dbContext.CommitTransactionAsync();
            }
            catch (Exception)
            {
                //dbContext.RollbackTransaction();
                throw;
            }
        }

这是他们调用方法

        public static Task ExecuteDbContextAsync<TDbContext>(Func<TDbContext,Task> action) where TDbContext : DbContext 
            => ExecuteScopeAsync<TDbContext>(sp => action(sp.GetService<TDbContext>()));

我为第一个尝试了类似的方法(以及许多其他迭代),但似乎无法正确使用语法

class Loginviewmodel: ObservableObject {

    @Published var email: String = ""
    @Published var password: String = ""

    @Published private (set) var errorAlert: Alerts? = nil
    @Published private (set) var token: Token? = nil

    private let webservice: Webservice
    private var cancellables = Set<AnyCancellable>()

    init(webservice: Webservice) {
        self.webservice = webservice
        
        $token
            .sink { token in
                KeychainWrapper.save(token: token)
            }
            .store(in: &cancellables)
    }

    func login() {
        let user = User(username: email,password: password)

        webservice
            .authenticate(user)
            .sink(receiveCompletion: { [weak self] completion in
                if completion == .failure(_) {
                    self?.errorAlert = .authenticationError
                }
            },receiveValue: { [weak self] token in
                self?.token = token
            })
            .store(in: &cancellables)
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)