Szymon Seliga
Szymon Seliga

Reputation: 824

Migrations not starting - Autofac throws an exception

I created a module that suppresses a dependency which in turn supresses Orchard.Users.Services.MembershipService

When I try to enable the module, orchard crashes with an exception:

Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor(...)' on type 'MembershipService'. 

With an inner exception of

System.Data.SqlClient.SqlException: Invalid object name 'MyModule_MyModel'

Ofcourse the table doesn't exit, but should be created as defined by Migrations.cs

using System;
using Orchard.Data;
using Orchard.Data.Migration;
using MyModule.Models;

namespace MyModule
{
    public class Migrations : DataMigrationImpl
    {
        private readonly IRepository<SettingsRecord> _repository;

        public Migrations(IRepository<SettingsRecord> repository)
        {
            _repository = repository;
        }

        public int Create()
        {
            SchemaBuilder.CreateTable("SettingsRecord", table => table
                    .Column<int>("Id", column => column.PrimaryKey().Identity())
                    .Column<string>("DefaultDomain")
                );

            return 1;
        }
    }
}

What can be the reason to why this migration doesn't start?

Update:

public MembershipService(
        IRepository<SettingsRecord> settingsRepository,
        IRepository<DomainRecord> domainsRepository,
        IOrchardServices orchardServices,
        IMessageManager messageManager,
        IEnumerable<IUserEventHandler> userEventHandlers,
        IClock clock,
        IEncryptionService encryptionService
        )
    {
        _settingsRepository = settingsRepository;
        _domainsRepository = domainsRepository;
        _orchardServices = orchardServices;
        _messageManager = messageManager;
        _userEventHandlers = userEventHandlers;
        _encryptionService = encryptionService;
        Logger = NullLogger.Instance;
        T = NullLocalizer.Instance;

        _defaultDomain = _settingsRepository.Table.FirstOrDefault().DefaultDomain;

        _baseMembershipService = new Orchard.Users.Services.MembershipService(orchardServices, messageManager, userEventHandlers, clock, encryptionService);
    }

Upvotes: 1

Views: 1773

Answers (1)

Piotr Szmyd
Piotr Szmyd

Reputation: 13366

This line is the source of your problem:

_defaultDomain = _settingsRepository.Table.FirstOrDefault().DefaultDomain;

Instead of setting this value in ctor, wrap it up in a property (and add null check).

Avoid putting any logic in ctor, besides simple assignments. Any error that happens there will most likely blow your site up.

Upvotes: 4

Related Questions