Error when create a new DependencyRegistrar for a plugin

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
12 年 前
Hi everyone,

I'm creating a new plugin in NopCommerce 2.1. However I keep getting this error when I add the DependencyRegistrar class

Server Error in '/' Application.

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Source Error:


Line 132:
Line 133:                            //init plugin type (only one plugin per assembly is allowed)
Line 134:                            foreach (var t in description.ReferencedAssembly.GetTypes())
Line 135:                                if (typeof(IPlugin).IsAssignableFrom(t))
Line 136:                                    if (!t.IsInterface)

Source File: C:\Users\Tri\Documents\Koneka\Koneka\NopCommerce\Main\Libraries\Nop.Core\Plugins\PluginManager.cs    Line: 134

Stack Trace:


[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) +0
   System.Reflection.RuntimeModule.GetTypes() +4
   System.Reflection.Assembly.GetTypes() +78
   Nop.Core.Plugins.PluginManager.Initialize() in C:\Users\Tri\Documents\Koneka\Koneka\NopCommerce\Main\Libraries\Nop.Core\Plugins\PluginManager.cs:134

[Exception: Could not initialise plugin folder]
   Nop.Core.Plugins.PluginManager.Initialize() in C:\Users\Tri\Documents\Koneka\Koneka\NopCommerce\Main\Libraries\Nop.Core\Plugins\PluginManager.cs:149

[Exception: Could not initialise plugin folder]
   Nop.Core.Plugins.PluginManager.Initialize() in C:\Users\Tri\Documents\Koneka\Koneka\NopCommerce\Main\Libraries\Nop.Core\Plugins\PluginManager.cs:157

[InvalidOperationException: The pre-application start initialization method Initialize on type Nop.Core.Plugins.PluginManager threw an exception with the following error message: Could not initialise plugin folder.]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +423
   System.Web.Compilation.BuildManager.CallPreStartInitMethods() +306
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +677

[HttpException (0x80004005): The pre-application start initialization method Initialize on type Nop.Core.Plugins.PluginManager threw an exception with the following error message: Could not initialise plugin folder.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9079228
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +258

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237

Here is the code of the class

using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;
using Nop.Core.Data;
using Nop.Core.Infrastructure;
using Nop.Core.Infrastructure.DependencyManagement;
using Nop.Data;
using Nop.Plugin.Koneka.Banners.Data;
using Nop.Plugin.Koneka.Banners.Models;

namespace Nop.Plugin.Koneka.Banners
{
    public class DependencyRegistrar:IDependencyRegistrar
    {
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new BannerRecordContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>("nop_object_context_koneka_banners")
                    .InstancePerHttpRequest();

                builder.Register<BannerRecordContext>(c => new BannerRecordContext(dataProviderSettings.DataConnectionString))
                    .InstancePerHttpRequest();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new BannerRecordContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>("nop_object_context_koneka_banners")
                    .InstancePerHttpRequest();

                builder.Register<BannerRecordContext>(c => new BannerRecordContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerHttpRequest();
            }

            /// override required repository with our custom context
            builder.RegisterType<EfRepository<Banner>>()
                .As<IRepository<Banner>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_koneka_banners"))
                .InstancePerHttpRequest();
        }

        public int Order
        {
            get { return 1; }
        }
    }
}


Please help.

Thanks in advance :)
12 年 前
Are you sure it is the dependency registrar and not the class you implemented BasePlugin on? I would do a quick review of the article below to make sure your plugin is setup correctly. I don't see anything immediately wrong with your registrar.

http://blog.csharpwebdeveloper.com/2011/09/10/writing-a-plugin-for-nopcommerce-2-x/
12 年 前
skyler.severns wrote:
Are you sure it is the dependency registrar and not the class you implemented BasePlugin on? I would do a quick review of the article below to make sure your plugin is setup correctly. I don't see anything immediately wrong with your registrar.

http://blog.csharpwebdeveloper.com/2011/09/10/writing-a-plugin-for-nopcommerce-2-x/


Thanks for your quick reply and the article. I read over the article, it is what I'm doing at the moment but my plugin is a standalone Plugins which use a part of Widget.

Here is the code of the BannersPlugin.cs

using System.Collections.Generic;
using System.Web.Routing;
using Nop.Core.Domain.Cms;
using Nop.Core.Plugins;
using Nop.Services.Cms;
using Nop.Services.Configuration;
using Nop.Plugin.Koneka.Banners.Data;

namespace Nop.Plugin.Koneka.Banners
{
    public class BannersPlugin:BasePlugin, IWidgetPlugin
    {
        private readonly IWidgetService _widgetService;
        private readonly BannerRecordContext _bannerContext;

        public BannersPlugin(IWidgetService widgetService)
        {
            _widgetService = widgetService;
        }

        public IList<WidgetZone> SupportedWidgetZones()
        {
            return new List<WidgetZone>()
            {
                WidgetZone.HeaderMenu,
                WidgetZone.BeforeRightSideColumn
            };
        }

        public void GetConfigurationRoute(int widgetId, out string actionName, out string controllerName, out RouteValueDictionary routeValues)
        {
            actionName = "Index";
            controllerName = "Banners";
            routeValues = new RouteValueDictionary {
                {"Namespaces", "Nop.Plugin.Koneka.Banners"},
                {"area", null},
                {"widgetId", widgetId}
            };
        }

        public void GetDisplayWidgetRoute(int widgetId, out string actionName, out string controllerName, out RouteValueDictionary routeValues)
        {
            actionName = "Display";
            controllerName = "Banners";
            routeValues = new RouteValueDictionary
            {
                {"Namespaces", "Nop.Plugin.Koneka.Banners"},
                {"area", null},
                {"widgetId", null}
            };
        }

        /// <summary>
        /// Instalation of the plugin
        /// </summary>
        public override void Install()
        {
            /// ---------------------
            /// Insert top banner widget after installation
            /// ---------------------
            Widget topBannerWidget = new Widget();
            topBannerWidget.DisplayOrder = 1;
            topBannerWidget.PluginSystemName = "Koneka.Banners";
            topBannerWidget.WidgetZone = WidgetZone.HeaderMenu;

            _widgetService.InsertWidget(topBannerWidget);
            //_bannerContext.Install();
            base.Install();
        }

        public override void Uninstall()
        {
            //_bannerContext.Uninstall();
            base.Uninstall();
        }
    }
}


Please let me know if I did something wrong above

Sincerely
12 年 前
Your code looks fine. It appears this might be from an invalid or incomplete build. Try cleaning the solution entirely, ensure all referenced assembles have "copy local = false" and try again.

https://www.nopcommerce.com/boards/t/11421/deploy-error.aspx?p=2
12 年 前
skyler.severns wrote:
Your code looks fine. It appears this might be from an invalid or incomplete build. Try cleaning the solution entirely, ensure all referenced assembles have "copy local = false" and try again.

https://www.nopcommerce.com/boards/t/11421/deploy-error.aspx?p=2


All of the referenced assembles are set "copy local = false". I also clean up the Solution and Build it again

I debugged the solution and the code breaks at

//init plugin type (only one plugin per assembly is allowed)
                            foreach (var t in description.ReferencedAssembly.GetTypes())
                                if (typeof(IPlugin).IsAssignableFrom(t))
                                    if (!t.IsInterface)
                                        if (t.IsClass && !t.IsAbstract)
                                        {
                                            description.PluginType = t;
                                            break;
                                        }
                            
                            referencedPlugins.Add(description);


which throws the exception

var fail = new Exception("Could not initialise plugin folder", ex);
                            Debug.WriteLine(fail.Message);
                            throw fail;


Any ideas?
12 年 前
Make sure that the dependencies of your plugin are also being copied to the plugins directory.
12 年 前
theonlylawislove wrote:
Make sure that the dependencies of your plugin are also being copied to the plugins directory.


My projects only depends on Nop.Data, Nop.Services, Nop.Web.Framework and Nop.Core.

What do I have to copy over the plugins directory?
12 年 前
triho wrote:
My projects only depends on Nop.Data, Nop.Services, Nop.Web.Framework and Nop.Core.

What do I have to copy over the plugins directory?

No, don't copy them. They're already referenced by the main web applciation
12 年 前
a.m. wrote:
My projects only depends on Nop.Data, Nop.Services, Nop.Web.Framework and Nop.Core.

What do I have to copy over the plugins directory?
No, don't copy them. They're already referenced by the main web applciation


Anyone knows what cause the errors in my plugin?
12 年 前
This plugin is to manipulate the Widgets component of NopCommerce 2.1 to put Banners into variables locations depends on users' selection. This plugin is an extended widget which has its own Configuration page and Display page depends on the type of the banner. This plugin has its own table in the database called Banner

So here is the code
the DOMAIN: Banner.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nop.Core;
using Nop.Core.Domain.Cms;

namespace Nop.Plugin.Koneka.Banners.Models
{
    public partial class Banner : BaseEntity
    {
        public int MyProperty { get; set; }

        public virtual int ZoneId { get; set; }

        public virtual string ImagePath { get; set; }

        public virtual DateTime Created { get; set; }

        public virtual DateTime Modified { get; set; }
    }
}


CONTROLLER: BannersController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Nop.Web.Framework.Controllers;
using Nop.Core.Data;
using Nop.Plugin.Koneka.Banners.Models;
using Nop.Plugin.Koneka.Banners.Data;

namespace Nop.Plugin.Koneka.Banners.Controllers
{
    [AdminAuthorize]
    public class BannersController : Controller
    {
        //private BannerRecordContext _dbContext = new BannerRecordContext();
        private IRepository<Banner> _bannerRepository;

        /// <summary>
        /// Main Constructor
        /// </summary>
        public BannersController()
        {
            /// Do nothing at the moment
            //_bannerRepository = bannerRepository;
        }

        public ViewResult Index()
        {
            //return View(_dbContext.Banners.ToList());
            return View();
        }

        public ViewResult Display()
        {
            Banner model = new Banner()
            {
                ImagePath = "http://google.come"
            };

            return View("Nop.Plugin.Koneka.Banners.Views.Banners.Display", model);
        }
    }
}


DATA:
BannerRecordMap.cs

using System.Data.Entity.ModelConfiguration;
using Nop.Plugin.Koneka.Banners.Models;

namespace Nop.Plugin.Koneka.Banners.Data
{
    public partial class BannerRecordMap : EntityTypeConfiguration<Banner>
    {
        public BannerRecordMap()
        {
            this.ToTable("Banner");
            this.HasKey(x => x.Id);
        }
    }
}


BannerRecordContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using Nop.Data;
using Nop.Core;
using System.Data.Entity.Infrastructure;
using Nop.Plugin.Koneka.Banners.Models;

namespace Nop.Plugin.Koneka.Banners.Data
{
    public class BannerRecordContext : DbContext, IDbContext
    {
        public BannerRecordContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            //((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
        }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new BannerRecordMap());

            //disable EdmMetadata generation
            modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
            base.OnModelCreating(modelBuilder);
        }

        public string CreateDatabaseScript()
        {
            return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
        }

        public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
        {
            return base.Set<TEntity>();
        }

        /// <summary>
        /// Install
        /// </summary>
        public void Install()
        {
            //create all tables
            //TODO don't create the table if it already exists
            var dbScript = CreateDatabaseScript();
            Database.ExecuteSqlCommand(dbScript);
            SaveChanges();
        }

        /// <summary>
        /// Uninstall
        /// </summary>
        public void Uninstall()
        {
            //TODO don't drop the table if it already exists
            var dbScript = "DROP TABLE Banner";
            Database.ExecuteSqlCommand(dbScript);
            SaveChanges();
        }
    }
}


PLUGIN file: BannerPlugin.cs

using System.Collections.Generic;
using System.Web.Routing;
using Nop.Core.Domain.Cms;
using Nop.Core.Plugins;
using Nop.Services.Cms;
using Nop.Services.Configuration;
using Nop.Plugin.Koneka.Banners.Data;

namespace Nop.Plugin.Koneka.Banners
{
    public class BannersPlugin:BasePlugin, IWidgetPlugin
    {
        private readonly IWidgetService _widgetService;

        public BannersPlugin(IWidgetService widgetService)
        {
            _widgetService = widgetService;
        }

        public IList<WidgetZone> SupportedWidgetZones()
        {
            return new List<WidgetZone>()
            {
                WidgetZone.HeaderMenu,
                WidgetZone.BeforeRightSideColumn
            };
        }

        public void GetConfigurationRoute(int widgetId, out string actionName, out string controllerName, out RouteValueDictionary routeValues)
        {
            actionName = "Index";
            controllerName = "Banners";
            routeValues = new RouteValueDictionary {
                {"Namespaces", "Nop.Plugin.Koneka.Banners"},
                {"area", null},
                {"widgetId", widgetId}
            };
        }

        public void GetDisplayWidgetRoute(int widgetId, out string actionName, out string controllerName, out RouteValueDictionary routeValues)
        {
            actionName = "Display";
            controllerName = "Banners";
            routeValues = new RouteValueDictionary
            {
                {"Namespaces", "Nop.Plugin.Koneka.Banners"},
                {"area", null},
                {"widgetId", null}
            };
        }

        /// <summary>
        /// Instalation of the plugin
        /// </summary>
        public override void Install()
        {
            /// ---------------------
            /// Insert top banner widget after installation
            /// ---------------------
            Widget topBannerWidget = new Widget();
            topBannerWidget.DisplayOrder = 1;
            topBannerWidget.PluginSystemName = "Koneka.Banners";
            topBannerWidget.WidgetZone = WidgetZone.HeaderMenu;

            _widgetService.InsertWidget(topBannerWidget);
            //_bannerContext.Install();
            base.Install();
        }

        public override void Uninstall()
        {
            //_bannerContext.Uninstall();
            base.Uninstall();
        }
    }
}


DEPENDENCY REGISTRAR: DependencyRegistrar.cs

using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;
using Nop.Core.Data;
using Nop.Core.Infrastructure;
using Nop.Core.Infrastructure.DependencyManagement;
using Nop.Data;
using Nop.Plugin.Koneka.Banners.Data;
using Nop.Plugin.Koneka.Banners.Models;

namespace Nop.Plugin.Koneka.Banners
{
    public class DependencyRegistrar:IDependencyRegistrar
    {
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new BannerRecordContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>("nop_object_context_koneka_banners")
                    .InstancePerHttpRequest();

                builder.Register<BannerRecordContext>(c => new BannerRecordContext(dataProviderSettings.DataConnectionString))
                    .InstancePerHttpRequest();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new BannerRecordContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>("nop_object_context_koneka_banners")
                    .InstancePerHttpRequest();

                builder.Register<BannerRecordContext>(c => new BannerRecordContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerHttpRequest();
            }

            /// override required repository with our custom context
            builder.RegisterType<EfRepository<Banner>>()
                .As<IRepository<Banner>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_koneka_banners"))
                .InstancePerHttpRequest();
        }

        public int Order
        {
            get { return 1; }
        }
    }
}



Anyone detects any errors in my code? Please help
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.