AutoConfiguredMoqCustomization with abstract class implementing interface - moq

I use AutoFixture 3.21.0, AutoFixture.AutoMoq 3.21.0, NUnit 2.6.3 and Moq 4.2.1409.1722.
I have the following interface, two abstract classes (one of them implements this interface), and two unit tests.
Tests pass.
public interface IMigration
{
IMigrationParameters MigrationParameters { get; set; }
}
public abstract class AbstractSutWithoutInterface
{
public IMigrationParameters MigrationParameters { get; set; }
}
public abstract class AbstractSutWithInterface : IMigration
{
public IMigrationParameters MigrationParameters { get; set; }
}
[TestFixture]
public class UnitTests
{
[Test]
public void TestAbstractSutWithoutInterface()
{
var fixture = new Fixture();
fixture.Customize( new AutoConfiguredMoqCustomization() );
var mock = fixture.Create<AbstractSutWithoutInterface>();
Assert.IsNotNull( mock.MigrationParameters ); // test passes
}
[Test]
public void TestAbstractSutWithInterface()
{
var fixture = new Fixture();
fixture.Customize( new AutoConfiguredMoqCustomization() );
var mock = fixture.Create<AbstractSutWithInterface>();
Assert.IsNull( mock.MigrationParameters ); // test passes
}
}
My question is why AutoConfiguredMoqCustomization has different behavior for abstract classes depending on whether property is defined by interface or not? In first test property is asserted to be not null but in second test is null. If classes are not abstract, property injection works as expected for both classes.

Update 2015/04/15
This bug has been fixed in AutoFixture.AutoMoq 3.24.2. See details here.
Update 2014/11/03
This is now being tracked on AutoFixture's GitHub, Issue 324.
Also, the last working version of Moq is 4.2.1402.2112, you can downgrade to that one instead of 4.0.
I can only reproduce this with the latest version of Moq (4.2.1409.1722).
I'm looking into this right now, and it seeeeems like a bug has been introduced in the latest version of Moq, but it might be by design, I'm not sure yet.
In the meantime, please use version 4.0.10827. To downgrade, go to Tools -> NuGet Packet Manager -> Package Manager Console and type:
Uninstall-Package Moq -Force
Install-Package Moq -Version 4.0.10827
I'll update this answer with my findings.

Related

No changes in model, should EF migration create empty empty Up() Down() methods? Or no migration at all?

I'm using EntityFrameworkCore Code First to create my SQL migration scripts.
After every change in my model, I run Add-Migration changeInModel and a corresponding XXXXXXXX_changeInModel.cs file is being generated in my Migrations folder.
If I don't make any change in my models AND I run Add-Migration noChangeInModel , I was assuming (out of nowhere) no generation of XXXXXX_noChangeInModel.cs
However, EF Core is creating a XXXXXX_noChangeInModel.cs with an empty Up and Down methods.
Is that supposed to be the expected behavior? Or should EF Core just skip the generation of an empty .cs file? I can't find any reference to this in the documentation.
I have taken my main project and stripped out all the code up to the bare minimum to find out whether is the behavior or some sort of bug in my configuration.
Below the minimum core to reproduce generating empty Up/Down methods with no change in models, with the following Nuget packages:
Microsoft.EntityFrameworkCore 2.2.6
Microsoft.EntityFrameworkCore.SqlServer 2.2.6
Microsoft.EntityFrameworkCore.Tools 2.2.6
Microsoft.NETCore.App 2.2.0
namespace TestingEFCore
{
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var connectionString = "Server=localhost;Database=TEST2;Integrated Security=SSPI;";
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer(connectionString);
return new BloggingContext(optionsBuilder.Options);
}
}
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
}
I would expect no XXXXXX_noChangeInModel.cs being generated, but a I get migrations with empty Up/Down methods. I can't find the documentation to describe this use case.
I think it is expected behavior. Consider the case when you have no changes in model but you need to add some data in your db like this
public partial class your_migration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(#"your sql");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(#"sql to clean up data");
}
}
Without an empty migration for no changes in model generated it would be impossible to obtain such migration.

Creating table Entity Framework Core and SQLite

Using Microsoft.EntityFrameworkCore.SQLite, I'm attempting to create a code level creation of a database, and add a simple row to a table. I get the error, SQLite error: no such table Jumplists.
From last to first, here are the classes
using JumpList_To_Clipboard.Data.Tables;
using Microsoft.EntityFrameworkCore;
namespace JumpList_To_Clipboard.Data
{
public class DataSQLite : IData
{
public const string DATABASE = "data.sqlite";
public DataSQLite()
{
using (var db = new SQLiteDbContext(DATABASE))
{
// Ensure database is created with all changes to tables applied
db.Database.Migrate();
db.JumpLists.Add(new JumpList { Name = "Default" });
db.SaveChanges(); // Exception thrown here
}
}
}
}
The DbContext class
using JumpList_To_Clipboard.Data.Tables;
using Microsoft.EntityFrameworkCore;
namespace JumpList_To_Clipboard.Data
{
class SQLiteDbContext : DbContext
{
readonly string db_path;
public DbSet<JumpList> JumpLists { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Item> Items { get; set; }
public SQLiteDbContext(string database) : base()
{
db_path = database;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(string.Format("Data Source={0}", db_path));
}
}
}
The JumpList class
using System.Collections.Generic;
namespace JumpList_To_Clipboard.Data.Tables
{
public class JumpList
{
public int JumpListId { get; set; }
public string Name { get; set; }
public List<Group> Groups { get; set; }
public List<Item> Items { get; set; }
}
}
The other two classes aren't worth repeating here, and don't give errors.
When I use the firefox sqlite extension to look at the data.sqlite file, none of my three tables are listed.
The command db.DataBase.Migrate says it
Applies any pending migrations for the context to the database.
What are pending migrations? I can't seem to find any documentation anywhere on these.
I'm combining examples from:
https://learn.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite
https://blogs.msdn.microsoft.com/dotnet/2016/09/29/implementing-seeding-custom-conventions-and-interceptors-in-ef-core-1-0/
Edit: If I replace db.Database.Migrate(); with db.Database.EnsureCreated(); it works. From the documentation, Migrate() is the same, but lets you create updates to the table structures, where EnsureCreated() does not. I'm confused.
So,
Microsoft has a serious issue making decent documentation, but I did find a site that has somewhat dated documentation for Learning Entity Framework Core, specifically migrations which is in the link.
At the top, it mentions,
If you have Visual Studio, you can use the Package Manager Console (PMC) to manage migrations.
Which led to the Package Manager Console page which states right at the top, that you need to have:
If you want to use the Package Manager Console to execute migrations command, you need to ensure that the latest version of Microsoft.EntityFrameworkCore.Tools is added to your project.json file.
The problem is, there is no project.json file anywhere in my project (or solution). After some searching, I found that via NuGet, to add Microsoft.EntityFrameworkCore.Tools
Then via Tools > NuGet Package Manager > Package Manager Console I was able to run the add-migration InitialDatabases command. The last part InitialDatabases is the name of the class it creates for you, and sticks in a folder called Migrations at the base of the project.
Now when:
context.Database.Migrate();
is run, all is well!
Try this (worked for me in a project a few months ago, i don't remember why):
public virtual DbSet<JumpList> JumpLists { get; set; }
public virtual DbSet<Group> Groups { get; set; }
public virtual DbSet<Item> Items { get; set; }
Also i had to use LONG instead of INT for classes ID because sqlite uses LONG as default for table ID, so after when you do a CRUD operation it fails because it can't compare/convert/cast LONG(64) to INT(32).

ExpressMapper, .NET Core, and Dependency Injection

I'm evaluating different object-to-object mappers for a .NET Core web API. One of the requirements I have is to use the built-in Dependency Injection container of .NET Core. I have tested Automapper, which is successful, but I'm interested in trying ExpressMapper. http://www.expressmapper.org/ The examples to configure are very sparse.
I see from Github page it appears to be .netcore ready.
https://github.com/fluentsprings/ExpressMapper
How can I configure ExpressMapper in startup.cs so that I can DI into a controller, similar to Automapper?
If someone had a quick startup.cs example for ExpressMapper and .NET Core that would be great.
(And as an aside, if someone was using another competitive mapper tool with .NET Core that they would recommend, that would also be helpful).
With Automapper I can add a MappingProfile class then do something like
Startup.cs
private MapperConfiguration _mapperConfiguration { get; set; }
_mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new MappingProfile());
});
ConfigureServices
services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());
Controller
public ValuesController(IMapper mapper)
{
_mapper = mapper;
}
The same with Expressmapper you can use IMappingServiceProvider interface and MappingServiceProvider implementation that Mapper static class uses. Please take a look at the following example and here is the link to see it in real:
public class Program
{
public static void Main()
{
var container = new Container();
container.Register<IMappingServiceProvider, MappingServiceProvider>();
var mapper = container.GetInstance<IMappingServiceProvider>();
var result = mapper.Map<Test, TestResponse>(new Test{Name = "Just a test"});
Console.WriteLine("result is {0} type", result as TestResponse);
Console.WriteLine("result.Name = {0}", result.Name);
}
public class Test{
public string Name {get;set;}
}
public class TestResponse{
public string Name {get;set;}
}
}

Autofac lazy property injection

I'm trying to inject business logic implementations into web API base controller. Somehow property in base controller is always null.
Also how can I do lazy injection?
Startups.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ViewBusinessLogic>().As<IViewBusinessLogic>().
PropertiesAutowired();
containerBuilder.Populate(services);
var container = containerBuilder.Build();
return container.Resolve<IServiceProvider>();
}
Interface, implementation and base controller:
public interface IViewBusinessLogic
{
IEnumerable<dynamic> GetView(Guid viewId);
}
public class ViewBusinessLogic : BusinessLogic, IViewBusinessLogic
{
public IEnumerable<dynamic> GetView(Guid viewId)
{
return new List<dynamic>
{
new { Test = "Test1" },
new { Test = "Test2" }
};
}
}
public abstract class BaseController : Controller
{
public IViewBusinessLogic ViewBusinessLogic { get; }
}
Controllers aren't resolved by the DI framework by default. You need to add AddControllerAsServices to have them be resolved by the DI of your choice.
From this GitHub issue:
Hi,
Maybe I'm wrong but as I tested deeply (and checked Mvc source code), Controllers are not resolved from IServiceProvider, but only constructor arguments of them are resolved from IServiceProvider.
Is that by design? I'm very suprised. Because, I'm using a different DI framework which supports property injection. And I can not use property injection since Controller instances are not requested from IServiceProvider.
Have you added AddControllersAsServices in your Startup (https://github.com/aspnet/Mvc/blob/ab76f743f4ee537939b69bdb9f79bfca35398545/test/WebSites/ControllersFromServicesWebSite/Startup.cs#L37)
The example above quoted for future reference.
public void ConfigureServices(IServiceCollection services)
{
var builder = services
.AddMvc()
.ConfigureApplicationPartManager(manager => manager.ApplicationParts.Clear())
.AddApplicationPart(typeof(TimeScheduleController).GetTypeInfo().Assembly)
.ConfigureApplicationPartManager(manager =>
{
manager.ApplicationParts.Add(new TypesPart(
typeof(AnotherController),
typeof(ComponentFromServicesViewComponent),
typeof(InServicesTagHelper)));
manager.FeatureProviders.Add(new AssemblyMetadataReferenceFeatureProvider());
})
// This here is important
.AddControllersAsServices()
.AddViewComponentsAsServices()
.AddTagHelpersAsServices();
services.AddTransient<QueryValueService>();
services.AddTransient<ValueService>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
As for the second part of your question: I don't think it's possible to have lazy instantiation via IoC container at all. Best fit for you is to create a factory class and inject the factory rather than the concrete service.
But usually you don't need lazy instantiation anyways, the instantiation of services should be fast. If it's not, you probably doing some funky stuff in the constructor (connecting somewhere, or doing other long running operations), which is an anti-pattern.

Dependency Injection into a AuthorizationFilterAttribute

I am pretty new to Unity & IoC in general & as usual, I have quickly got myself into a bind...
I have created an Authorization Filter Attribute for the ASP.NET Web API Beta. I now need to inject my Authorizer into the Attribute however since this is an attribute I cannot simply do this public TestAuthAttribute(IAuthorizer Authorizer) in my constructor.
So I then decided to create a public property decorated with the [Dependency] attribute for property injection however it does not get resolved.
Here is the code:
public class TestAuthAttribute : AuthorizationFilterAttribute
{
[Dependency]
public IAuthorizer Authorizer { get; set; }
public TestAuthAttribute() {
...
}
private bool authorizeCore(HttpRequestMessage request)
{
if (Authorizer == null)
throw Error.ArgumentNull("Null Authorizer"); // <<<<< this is null
}
When the controller is decorated with the [TestAuth] the Attribute is triggered but the Authorizer is not resolved, it is null)
I have placed the following code in my controller & Authorizer does get resolved...
[Dependency]
public IAuthorizer Authorizer { get; set; }
Why is this dependency not resolved in my AuthorizationFilterAttribute & how would you go about Injecting the Authorizer into the AuthorizationFilterAttribute?
Full disclosure: I have not used Turbine.
Having said that, I think it might solve your problem for you or at least show you how to solve it.
They have a Unity Nuget package here: http://nuget.org/packages/MvcTurbine.Unity
And you can find more detail on their codeplex site here: http://mvcturbine.codeplex.com/
Hope that helps.
I use Ninject for similar purpose. I do have a reference to Ninject.Web.WebAPI which works perfectly.
However, this does not seem working with MVC4 RC.

Resources