osharp3 整合 dbcontextscope 文章2 将dbcontext的创建收回到ioc管理

osharp3 整合 dbcontextscope 后,,dbcontextscope 对dbcontext管理的很好,做到,用到时创建,不用时销毁,下面看一个 trace

aspx.page: End PreInit
aspx.page: Begin Init
aspx.page: End Init
aspx.page: Begin InitComplete
aspx.page: End InitComplete
aspx.page: Begin PreLoad
aspx.page: End PreLoad
aspx.page: Begin Load
trace OnLoad: SetControlInPage begin 根据权限标记,控制页面控件的显示和隐藏
trace OnLoad: RegBtnClick begin 根据权限标记,注册按钮事件
: DefaultDbContext ctor


object name: System.String
caller name: CanDoo.Data.Entity.Interceptors.EFIntercepterLogging
member name: ReaderExecuted
source line number: 94
time: 20160705 071119 8589791
message: ReaderExecuted执行时间:0 毫秒 \r\n -->ReaderExecuted.Command:\r\nSELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[CreatedTime] AS [CreatedTime],
    [Extent1].[Code] AS [Code],
    [Extent1].[SortIndex] AS [SortIndex],
    [Extent1].[Remark] AS [Remark],
    [Extent1].[ParentId] AS [ParentId],
    [Extent1].[Name] AS [Name]
    FROM [dbo].[sys_Department] AS [Extent1]


: DefaultDbContext Dispose
aspx.page: End Load
aspx.page: Begin LoadComplete
aspx.page: End LoadComplete
aspx.page: Begin PreRender
aspx.page: End PreRender
aspx.page: Begin PreRenderComplete
aspx.page: End PreRenderComplete
aspx.page: Begin SaveState
aspx.page: End SaveState
aspx.page: Begin SaveStateComplete
aspx.page: End SaveStateComplete
aspx.page: Begin Render
aspx.page: End Render

但dbcontext默认是由dbcontextscope创建的,所以,我们的ioc就不能对dbcontext建行注入

不过它留了个接口 IDbContextFactory

    public interface IDbContextFactory
    {
		TDbContext CreateDbContext<TDbContext>() where TDbContext : DbContext;
        DbContext CreateDbContext(Type requestedType);
    }

为了在dbcontext注入属性,,我通过这个接口,

将dbcontext的创建收回到ioc,实现这个接口

    public class CandooDbContextFactory : IDbContextFactory
    {
        private IServiceProvider _provider;
        public CandooDbContextFactory(IServiceProvider provider)
        {
            _provider = provider;
        }
        public TDbContext CreateDbContext<TDbContext>() where TDbContext : DbContext
        {
            return (TDbContext)_provider.GetService(typeof(TDbContext));
        }

        public DbContext CreateDbContext(Type requestedType)
        {
            return (DbContext)_provider.GetService(requestedType);
        }
    }

修改Startup注入配置

            services.AddTransient<DefaultDbContext>();
            services.AddTransient<LoggingDbContext>();
            services.AddScoped<IDbContextFactory, CandooDbContextFactory>();

相关文章:

osharp3使用经验:整合DbContextScope 文章 1 http://www.cnblogs.com/shiningrise/p/oshap3_DbContextScope.html

https://github.com/mehdime/DbContextScope

https://github.com/i66soft/osharp

你可能感兴趣的:(osharp3 整合 dbcontextscope 文章2 将dbcontext的创建收回到ioc管理)