Commit de1715b7 authored by yangxiaodong's avatar yangxiaodong

modify exensions

parent 6cd22867
using System;
using System.Reflection;
using Cap.Consistency;
using Cap.Consistency.EntityFrameworkCore;
using Cap.Consistency.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Cap.Consistency.EntityFrameworkCore
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Contains extension methods to <see cref="ConsistencyBuilder"/> for adding entity framework stores.
......@@ -18,34 +20,23 @@ namespace Cap.Consistency.EntityFrameworkCore
/// <returns>The <see cref="ConsistencyBuilder"/> instance this method extends.</returns>
public static ConsistencyBuilder AddEntityFrameworkStores<TContext>(this ConsistencyBuilder builder)
where TContext : DbContext {
builder.Services.TryAdd(GetDefaultServices(builder.MessageType, typeof(TContext)));
return builder;
}
/// <summary>
/// Adds an Entity Framework implementation of message stores.
/// </summary>
/// <typeparam name="TContext">The Entity Framework database context to use.</typeparam>
/// <typeparam name="TKey">The type of the primary key used for the users and roles.</typeparam>
/// <param name="builder">The <see cref="ConsistencyBuilder"/> instance this method extends.</param>
/// <returns>The <see cref="ConsistencyBuilder"/> instance this method extends.</returns>
public static ConsistencyBuilder AddEntityFrameworkStores<TContext, TKey>(this ConsistencyBuilder builder)
where TContext : DbContext
where TKey : IEquatable<TKey> {
builder.Services.TryAdd(GetDefaultServices(builder.MessageType, typeof(TContext), typeof(TKey)));
builder.Services.AddScoped(typeof(IConsistencyMessageStore<>).MakeGenericType(builder.MessageType),
typeof(ConsistencyMessageStore<,>).MakeGenericType(typeof(ConsistencyMessage), typeof(TContext)));
return builder;
}
private static IServiceCollection GetDefaultServices(Type messageType, Type contextType, Type keyType = null) {
Type messageStoreType;
keyType = keyType ?? typeof(string);
messageStoreType = typeof(IConsistencyMessageStore<>).MakeGenericType(messageType, contextType, keyType);
var services = new ServiceCollection();
services.AddScoped(
typeof(IConsistencyMessageStore<>).MakeGenericType(messageStoreType),
messageStoreType);
return services;
private static TypeInfo FindGenericBaseType(Type currentType, Type genericBaseType) {
var type = currentType.GetTypeInfo();
while (type.BaseType != null) {
type = type.BaseType.GetTypeInfo();
var genericType = type.IsGenericType ? type.GetGenericTypeDefinition() : null;
if (genericType != null && genericType == genericBaseType) {
return type;
}
}
return null;
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment