Setting ASP.NET MVC ControllerFactory has no effect - asp.net-mvc

I'm trying to have my ASP.NET MVC2 controllers built using StructureMap but ASP.NET doesn't seem to remember that I've called ControllerBuilder.Current.SetControllerFactory in my Global.asax file.
Specifically I get the error that my controller has no parameterless constructor. The stack trace reveals that my custom ControllerFactory was never actually executed.
Here is my call to the method that should tell ASP.NET which ControllerFactory to use:
Sub Application_Start()
RegisterRoutes(RouteTable.Routes)
ControllerBuilder.Current.SetControllerFactory(GetType(StructureMapControllerFactory))
BootStrapper.RegisterDependencies()
End Sub
And here's the exception that I receive.
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
Why is ASP.NET forgetting which ControllerFactory to use?

How is your StructureMapControllerFactory defined? Does it have a default constructor?
If not, try using that second overload of the SetControllerFactory method:
// First create the controllerFactory instance...
ControllerBuilder.Current.SetControllerFactory(controllerFactory);

You have to set your controllerFactory before you RegisterRoutes...

Related

Execution permission cannot be acquired - FileLoadException: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime

I'm trying to setup an old MVC 3 Application on my development machine and trying to make it work. I'm getting he following error. I'm not sure how to resolve this. I appreciate any help over this.
Execution permission cannot be acquired.
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.Security.Policy.PolicyException: Execution permission cannot be acquired.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[PolicyException: Execution permission cannot be acquired.]
System.Security.CodeAccessSecurityEngine.TryResolveGrantSet(Evidence evidence, PermissionSet& grantSet) +11652088
System.Security.CodeAccessSecurityEngine.ResolveGrantSet(Evidence evidence, Int32& specialFlags, Boolean checkExecutionPermission) +44
[FileLoadException: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416)]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark) +102
System.Reflection.Assembly.LoadFrom(String assemblyFile) +34
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.GetRuntimeAssemblyFromRegistry(Assembly& runtime) +23
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.LoadRuntime() +21
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.PreApplicationStart() +46
[InvalidOperationException: The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +613
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531
[HttpException (0x80004005): The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9946132
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261

Could not load type 'ImageResizer.Util.BundleAttribute'

On Jan 1st. i installed NopCommerce on my hosted website - complete clean installation. NopCommerce uses the ImageReszier component managed via NuGet in Visual studio.
NopCommerce runes with out any problems on my local installation from the same date but i get the following error when i try to run it on my hosted website.
Could not load type 'ImageResizer.Util.BundleAttribute'
I use ImageResizer version: 4.0.4.934
Stack Trace:
[TypeLoadException: Could not load type 'ImageResizer.Util.BundleAttribute' from assembly 'ImageResizer, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null'.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +152
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +158
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +91
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +438
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Type attributeType, Boolean inherit) +64
WebActivator.AssemblyExtensions.GetActivationAttributes(Assembly assembly) +126
WebActivator.ActivationManager.RunActivationMethods() +220
WebActivator.ActivationManager.RunPreStartMethods() +28
WebActivator.ActivationManager.Run() +61
[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Could not load type 'ImageResizer.Util.BundleAttribute' from assembly 'ImageResizer, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null'..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +613
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Could not load type 'ImageResizer.Util.BundleAttribute' from assembly 'ImageResizer, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null'..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9923092
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.114.0
Problem solved. I ended up by deleting everything and did a clean installation again. Now it's working.
You may download wrong plugin S3Reader or AzureReader.
If you are using S3 replace nuget package ImageResizer.Plugins.S3Reader with ImageResizer.Plugins.S3Reader2
I faced the same issue and after deleting everything in the bin folder and rebuilding the solution, it worked for me !!

Invalid object name 'dbo.__MigrationHistory' using Database.Create; EF6.02 when connection string is passed in

I experience an error when trying to create a database using the following code.
Note the problem does not happen if the connection string is not passed in.
Also the problem happens when I run the program in the IDE. It does not happen if I run the program .exe or if I run the unit tests within the IDE.
However if the database is created by running the unit tests or by running the .EXE then the __MigrationHistory table is created in the main tables section, not the system tables.
public Context(string connString, bool AddInitialRecords )
: base(connString ?? "MyContextName")
{
this.CheckDatabase(AddInitialRecords);
}
public void CheckDatabase(bool AddInitialRecords)
{
if (this.Database.Exists())
{
// upgrade stuff
}
else
{
Database.Create(); // error occurs here
// seeding stuff
}
}
I don't get the problem if I just use something like
var db1 = new Context();
db1.Database.CreateIfNotExists();
I have found some documentation here but it confuses me. I am installing from a "stable build" surely I aren't experiencing something from 2012? What could I be doing wrong with PM?
The error message for the problem is....
System.Data.Entity.Core.EntityCommandExecutionException occurred
HResult=-2146232004 Message=An error occurred while executing the
command definition. See the inner exception for details.
Source=EntityFramework StackTrace:
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) InnerException:
System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Invalid object name 'dbo.__MigrationHistory'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=208
Procedure=""
Server=.\SQLEXPRESS
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource`1 completion, Int32 timeout, Task& task,
Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.b__8()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1
operation, TInterceptionContext interceptionContext, Action`1
executing, Action`1 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior)
InnerException:
This happens because EF does some probing for the __MigrationsHistory table. For instance you can use EF with an existing database that was not created using EF Migrations but EF has no way of knowing it so it tries to connect to the database and uses the table to check this. If the table does not exist an exception will be thrown. EF then catches the exception and does the right thing (e.g. creates the __MigrationsHistory table if needed or proceeds without using migrations).
In general you won't see this exception when running without the debugger. However when debugging your code AND when the option to break the execution when an exception is thrown is set you will see all the exceptions that are being thrown even if they are internally handled and never reach your code. The default setting is not to break when the exception is thrown but only when an exception that is not being handled is thrown. You can change the setting by checking/unchecking a check box in the "Thrown" column in the Debug -> Exceptions dialog.
In VS 2017 you open exception settings using Debug->Windows->Exception Settings. If you right-click on the "Common Language Runtime Exceptions" you can select the "Restore Defaults" which disables breaking your program when most of the exceptions are thrown.
You can turn off code first database initialization for your database, by adding this to your context's constructor:
System.Data.Entity.Database.SetInitializer<YourContext>(null);
This should prevent the attempt to access dbo.__MigrationHistory.
I faced the same issue. It means that EF is not able to find the __Migration history table. also note for some reason it has to be dbo.__MigrationHistory (note dbo). Ensure that you have run "update-database" atleast once before running the Context
I forgot to add the database name in my connection string. After I added, it started to work
Just uncheck break checkbox then click enable editing to proceed
the database I was using Table __MigrationHistory was missing, so when I Scripted migrations, it generated this code:
IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL
BEGIN
CREATE TABLE [__EFMigrationsHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
);
END;
and This fixed..

Why are my controllers being instantiated when they're not being called?

Here are the symptoms I am experiencing:
I have a brand new empty controller in an area:
public class JamController : Controller
{
public JamController()
{
throw new Exception("Not implemented!");
}
If I visit http://myprojectserver.example.com:12345/urlthatdoesnotexist, I get the following error:
[CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Not implemented!
Resulting in: An exception occurred while trying to create an instance of type 'MyWebProject.Areas.Users.Controllers.JamController'.
Resulting in: Cannot activate part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController --> MyWebProject.Areas.Users.Controllers.JamController
Resulting in: Cannot get export 'MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")' from part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")
]
System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) +55
System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart) +78
System.ComponentModel.Composition.Hosting.CatalogExport.GetExportedValueCore() +47
System.ComponentModel.Composition.Primitives.Export.get_Value() +57
System.ComponentModel.Composition.ExportServices.GetCastedExportedValue(Export export) +40
System.ComponentModel.Composition.<>c__DisplayClassa`1.<CreateStronglyTypedLazyOfT>b__6() +39
System.Lazy`1.CreateValue() +416
System.Lazy`1.LazyInitValue() +382
System.Lazy`1.get_Value() +75
MefContrib.Web.Mvc.<>c__DisplayClass4.<GetControllerType>b__0(Lazy`1 e) +53
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +204
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
MefContrib.Web.Mvc.CompositionControllerFactory.GetControllerType(RequestContext requestContext, String controllerName) +412
System.Web.Mvc.DefaultControllerFactory.System.Web.Mvc.IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, String controllerName) +61
System.Web.Mvc.MvcRouteHandler.GetSessionStateBehavior(RequestContext requestContext) +122
System.Web.Mvc.MvcRouteHandler.GetHttpHandler(RequestContext requestContext) +33
System.Web.Mvc.MvcRouteHandler.System.Web.Routing.IRouteHandler.GetHttpHandler(RequestContext requestContext) +10
System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) +9709884
System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +82
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +699
My question is "Why?" Why on earth is it trying to instantiate this controller? Where do I look to determine what is causing this. I'm pretty sure it isn't expected behaviour to instantiate every controller on "page not found".
I'm at a loss to know where to look. Can someone point me in the direction of something that will help?
UPDATE:
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).
This is down to a bug in MefContrib.Web.Mvc. This assembly implements it's own ControllerFactory that inherits from DefaultControllerFactory.
The factory overrides GetControllerType, I assume to try and resolve controllers that live in assemblies somewhere other than the default application or it's references. The implementation of GetControllerType first calls into base.GetControllerType to see if Defaultcontroller can resolve it.
If it can't - which is the case for urls that don't exist - it asks MEF for all exports that implement IController. This returns an IEnumerable<Lazy<IController>> with one item for every class that implements IController in the bin/ folder (by default).
It then runs a linq query over the IEnumerable, calling GetType() on the Value property of each Lazy<IController>. Requesting the Value of a Lazy<T> forces the instance to be created. This is why every controller in the bin/ is being constructed for a page that doesn't exist.
I don't think this is an easy problem to fix properly as there is no way of getting the Type instance from Lazy<T>.Value without creating the value. However by removing the lines from AppStart_MefContribMVC3.cs that register the ControllerFactory with Asp.Net - you have effectively stopped using MefContrib.Web.Mvc's ControllerFactory and just used Asp.Net's DefaultControllerFactory instead.
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).

Different dlls in Entity Framework Code First Migrations

I have a MVC 4 Project (Company.Project.WebUI), a project for all my model classes (Company.Project.Data) and a project for the DAL (Company.Project.Services).
How can I manage this with Code First Migrations?
I'm getting the following error when I write the command Add-Migration Init:
`
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.GetPendingMigrationsRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
`
When I write the command Add-Migration -StartUpProjectName "Company.Project.Services" Init I'll get also an error
`
System.IO.FileNotFoundException: Could not load file or assembly 'Company.Project.WebUI' or one of its dependencies. The system cannot find the file specified.
File name: 'Company.Project.WebUI'
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.GetPendingMigrationsRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
`
Could somebody tell me what's the best way to use EF Code First Migration with different dlls?
I don't know why, but EF wants your DAL project to be set as the start up project in Visual Studio. I just had the same error and this solved the problem.
On Solution Explorer: Right Click to your DAL project -> select "Set as StartUp Project".

Resources