SimpleInjector的配置无效错误

时间:2014-07-01 04:27:34

标签: c# asp.net simple-injector

错误消息:

配置无效。为UserController类型创建实例失败。 UserController类型的已注册委托引发了异常。 IApplicationDatabaseFactory类型的已注册委托返回null。

我有两个数据库,我正在使用实体框架。

以下是代码的链接:https://onedrive.live.com/redir?resid=738F28AF693709DC!388&authkey=!ALw3VMi6GEaiTZg&ithint=file%2c.zip

https://onedrive.live.com/redir?resid=738F28AF693709DC!391&authkey=!AJZ2fPbU7CBctYw&ithint=folder%2c

我需要帮助配置SimpleInjector。

有两个数据库1.SWT DB 2.授权DB
SWT DB具有RegionRepository Auth DB具有UserRepository。 它们都在构造函数中有CommandHandler,它们使用DBInstance。必须将SimpleInjector配置为将正确的DB实例传递给存储库。

这是配置发生的Global.ascx代码,在Application_Start()中配置simpleInjector需要帮助

 protected void Application_Start()
    {

        var container = new Container();

        var services = GlobalConfiguration.Configuration.Services;
        var controllerTypes = services.GetHttpControllerTypeResolver()
            .GetControllerTypes(services.GetAssembliesResolver());

        foreach (var controllerType in controllerTypes)
        {
            container.Register(controllerType);
        }

        container.RegisterAll<DbContext>(typeof(SWDMSEntities), typeof(TicketingDBEntities));

        container.Register<IAuthorizationDatabaseFactory>(() => new AuthorizationDatabaseFactory(new SWDMSEntities()), Lifestyle.Singleton);
        container.Register<ISWTDatabaseFactory>(() => new SWTDatabaseFactory(new TicketingDBEntities()), Lifestyle.Singleton);

        //container.RegisterAll<IApplicationDatabaseFactory>(typeof(AuthorizationDatabaseFactory), typeof(SWTDatabaseFactory));

        //registering 
        ////container.RegisterAll<IEntityCommand>(typeof(AddEntityCommand), typeof(DeleteEntityCommand));


        //// Register the command handler
        container.Register<ICommandHandler<AddEntityCommand>, AddEntityCommandHandler>();
        container.Register<ICommandHandler<UpdateEntityCommand>, UpdateEntityCommandHandler>();
        container.Register<ICommandHandler<DeleteEntityCommand>, DeleteEntityCommandHandler>();

        //// Go look in all assemblies and register all implementations
        //// of ICommandHandler<T> by their closed interface:

        ////container.RegisterManyForOpenGeneric(
        ////    typeof(ICommandHandler<>),
        ////    AppDomain.CurrentDomain.GetAssemblies());

        container.RegisterManyForOpenGeneric(
            typeof(ICommandHandler<>),
            typeof(ICommandHandler<>).Assembly);

        // Decorate each returned ICommandHandler<T> object with
        // a InfoLoggingCommandHandlerDecorator<T>.
        container.RegisterDecorator(
            typeof(ICommandHandler<>),
            typeof(InfoLoggingCommandHandlerDecorator<>));

        // Decorate each returned ICommandHandler<T> object with
        // a AuthorizationCommandHandlerDecorator<T>.
        container.RegisterDecorator(
            typeof(ICommandHandler<>),
            typeof(AuthorizationCommandHandlerDecorator<>));


        var lifestyle = new LifetimeScopeLifestyle();

        var Authdb = new InstanceProducer(typeof(IAuthorizationDatabaseFactory),
                lifestyle.CreateRegistration<IAuthorizationDatabaseFactory>(
                () => new AuthorizationDatabaseFactory(new SWDMSEntities()), container));

        var Appdb = new InstanceProducer(typeof(ISWTDatabaseFactory),
                lifestyle.CreateRegistration<ISWTDatabaseFactory>(
                () => new SWTDatabaseFactory(new TicketingDBEntities()), container));


        container.RegisterWithContext<IApplicationDatabaseFactory>(context =>
        {
            Type commandType = context.ServiceType.GetGenericArguments().Single();

            if (context.ImplementationType == typeof(IAuthorizationDatabaseFactory))
            {
                return container.GetInstance<IAuthorizationDatabaseFactory>();
                //return (IApplicationDatabaseFactory)Authdb.GetInstance();
            }
            else if (context.ImplementationType == typeof(ISWTDatabaseFactory))
            {
                return container.GetInstance<ISWTDatabaseFactory>();
                // return (IApplicationDatabaseFactory)Appdb.GetInstance();
            }
            else
            {
                return null;
            }
        });       


        //// Register your types, for instance:
        container.Register<IUserRepository, UserRepository>();
        container.Register<IRegionRepository, RegionRepository>();

        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

        // Verify the container configuration
        container.Verify();

        // Register the dependency resolver.
        GlobalConfiguration.Configuration.DependencyResolver =
            new SimpleInjectorWebApiDependencyResolver(container);
    }

以下是接口和类

 public interface IApplicationDatabaseFactory :
    IDisposable
{
    DbContext GetContext();
}

public interface ISWTDatabaseFactory :
    IApplicationDatabaseFactory
{
}

 public interface IAuthorizationDatabaseFactory :
    IApplicationDatabaseFactory
{
}

 public abstract class ApplicationDatabaseFactoryBase :
    IApplicationDatabaseFactory
{
    private DbContext dataContext;
    private bool isDisposed;
    public ApplicationDatabaseFactoryBase(DbContext dBContext)
    {
        dBContext.Configuration.LazyLoadingEnabled = false;  ////Do not remove these lines as they are required
        dBContext.Configuration.ProxyCreationEnabled = false; ////Do not remove these lines as they are required
        this.dataContext = dBContext;
    }

    ~ApplicationDatabaseFactoryBase()
    {
        this.Dispose(false);
    }

    public DbContext GetContext()
    {
        return this.dataContext;
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void DisposeCore()
    {
        if (this.dataContext != null)
        {
            this.dataContext.Dispose();
        }
    }

    private void Dispose(bool disposing)
    {
        if (!this.isDisposed && disposing)
        {
            this.DisposeCore();
        }

        this.isDisposed = true;
    }
}

public class SWTDatabaseFactory :
    ApplicationDatabaseFactoryBase,
    ISWTDatabaseFactory
{
    public SWTDatabaseFactory( TicketingDBEntities  dBContext) :
        base((DbContext)dBContext)
    {
    }

    ~SWTDatabaseFactory()
    {
        this.Dispose();
    }
}

 public class AuthorizationDatabaseFactory : 
    ApplicationDatabaseFactoryBase,
    IAuthorizationDatabaseFactory
{       
    public AuthorizationDatabaseFactory(SWDMSEntities dbContext) :
        base((DbContext)dbContext)
    {
    }

    ~AuthorizationDatabaseFactory()
    {
        this.Dispose();
    }
}

public interface IRegionRepository :
    IRepository<Region>
{
}

 public class RegionRepository :
    RepositoryBase<Region>,
    IRegionRepository
{
    public RegionRepository(
        ISWTDatabaseFactory databaseFactory,
        ICommandHandler<AddEntityCommand> addEntityCommandHandler,
        ICommandHandler<UpdateEntityCommand> updateEntityCommandHandler,
        ICommandHandler<DeleteEntityCommand> deleteEntityCommandHandler)
        : base((IApplicationDatabaseFactory)databaseFactory, addEntityCommandHandler, updateEntityCommandHandler, deleteEntityCommandHandler)
    {
    }
}

 public interface IUserRepository :
   IRepository<Authorization_User>
{        
}

 public class UserRepository :
    RepositoryBase<Authorization_User>,
    IUserRepository
{
    public UserRepository(
        IAuthorizationDatabaseFactory databaseFactory,
        ICommandHandler<AddEntityCommand> addEntityCommandHandler,
        ICommandHandler<UpdateEntityCommand> updateEntityCommandHandler,
        ICommandHandler<DeleteEntityCommand> deleteEntityCommandHandler)
        : base(databaseFactory, addEntityCommandHandler, updateEntityCommandHandler, deleteEntityCommandHandler)
    {
    }
}

 public class AddEntityCommandHandler : 
    EntityCommandHandlerBase,
    ICommandHandler<AddEntityCommand>
{
    public AddEntityCommandHandler(IApplicationDatabaseFactory databaseFactory) :
        base(databaseFactory)
    {
    }
    public Execute(AddEntityCommand addEntityCommand)
    {
    }
}

1 个答案:

答案 0 :(得分:1)

您已将null编码为IApplicationDatabaseFactory

的返回类型
container.RegisterWithContext<IApplicationDatabaseFactory>(context =>
{
    Type commandType = context.ServiceType.GetGenericArguments().Single();

    if (context.ImplementationType == typeof(IAuthorizationDatabaseFactory))
    {
        return container.GetInstance<IAuthorizationDatabaseFactory>();
    }
    else if (context.ImplementationType == typeof(ISWTDatabaseFactory))
    {
        return container.GetInstance<ISWTDatabaseFactory>();
    }
    else
    {
        // see here
        return null;
    }
});

我也认为context.ImplementationType == typeof(IAuthorizationDatabaseFactory)永远不会成真。尝试这样的事情:

container.RegisterWithContext<IApplicationDatabaseFactory>(context =>
{
    if (typeof(IAuthorizationDatabaseFactory)
        .IsAssignableFrom(context.ImplementationType))
    {
        return container.GetInstance<IAuthorizationDatabaseFactory>();
    }
    else if (typeof(ISWTDatabaseFactory)
        .IsAssignableFrom(context.ImplementationType))
    {
        return container.GetInstance<ISWTDatabaseFactory>();
    }
    else
    {
        throw new InvalidOperationException();
    }
}); 

好的,我现在可以看到commandType的内容 - 你会想要下面的代码,它会尝试返回IAuthorizationDatabaseFactory的{​​{1}}

ICommandHandler<AddEntityCommand>