Migrating from Unity, how to do Property or MethodInjection on all classes without registering them - autofac

Ok, lets first be clear that I know this is not correct way (use constructor injection). I do have a huge codebase to take care of and a refactoring is not an option right now.
I have a base class
public abstract class ServiceBase {
public IUnitOfWork UnitOfWork {get;set;}
}
and a lot of Concrete classes that are NOT registered in the contianer.
public class ServiceScript : ServiceBase {
}
How do I inject IUnitOfWork??
I have alot of this ServiceScript-classes that are not registred in the Container
but is using the AnyConcreteTypeNotAlreadyRegisteredSource in Autofac
In unity I did just mark my PropertyDependency with a [Dependency]-attribute and everything just works.
It looks like StructureMap has the same way of using attributes, but they don't have Prism/Xamarin-support, like Autofac has.
This same problem can be applied to a ControllerX : ControllerBase in asp.net core.
I have tried to solve this with a RegistrationSource, but can't get it to work in the controller case that I tried first.
Any input??
/Peter

Related

Am I properly creating my interface for a partial DbContext class in EF6?

I am utilizing ASP.NET WebAPI 2 & EF6 for a very small project which utilizes AutoFac to inject my DbContext directly into my controllers. I am not using a repository pattern as per Ryan's answer here: NOT using repository pattern, use the ORM as is (EF). To perform the injection, I went ahead and created an interface like so:
public interface IMoveGroupEntities : IDisposable
{
System.Data.Entity.DbSet<HostEntry> HostEntries { get; set; }
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
Task<int> SaveChangesAsync();
}
Then implemented the interface on a partial class which sits in conjunction with my generated entities like so:
public partial class MoveGroupEntities : IMoveGroupEntities
{
}
I have a sneaking suspicion I'm doing something incorrectly here as I feel like this line:
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
Shouldn't be needed, but it does appear to be necessary as "Entry" is used from within my scaffolded API controller.
Can anyone chime in here on a better way to achieve this?
The best you can say about scaffolded code is: it works. It's not the best code architecturally. I fully agree with the link you quote, but that doesn't mean that the controllers should be in touch with EF artifacts directly (including Entry).
I think it's a mistake to replace one DbSet wrapper (repository) by another wrapper. The gist of the answer is: use the context (and DbSets, etc.) directly in your code. That is: don't use wrappers. That is not: use contexts (etc.) anywhere. You're doing the exact opposite: you create a different type of wrapper in order to use EF anywhere. But it's a good thing that your gut feeling doesn't really like it.
I always prefer to keep action methods (MVC, Web API) small. Basically, I just make them call a service method. It's the service that deals with contexts and everything EF has to offer. These services may be in a separate assembly, but wherever they are, they are injected into the controllers by dependency injection and, likewise, they obtain their contexts by DI.

SetExecutionStrategy to SqlAzureExecutionStrategy with DbMigrationsConfiguration?

I saw a post today about implementing SqlAzureExecutionStrategy:
http://romiller.com/tag/sqlazureexecutionstrategy/
However, all examples I can find of this use a Configuration that inherits from DbConfiguration. My project is using EF6 Code First Migrations, and the Configuration it created inherits from DbMigrationsConfiguration. This class doesn't contain a definition for SetExecutionStrategy, and I can find no examples that actually combine SqlAzureExecutionStrategy (or any SetExecutionStrategy) with DbMigrationsConfiguration.
Can this be done?
If anyone else comes across this question, this is what we figured out:
Create a custom class that inherits from DbConfiguration (which has SetExecutionStrategy):
public class DataContextConfiguration : DbConfiguration
{
public DataContextConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
}
}
Then add this attribute to your DataContext, specifying that it is to use your custom class:
[DbConfigurationType(typeof(DataContextConfiguration))]
public class DataContext : DbContext, IDataContext
{
...
}
After more investigation, now I think the correct answer is that:
DbMigrationsConfiguration is completely separate and only configures the migration settings. That's why it doesn't inherit from or have the same options as DbConfiguration.
It is not loaded, and is irrelevant, for actual operation.
So you can (and should) declare a separate class based on DbConfiguration to configure the runtime behaviour.
I added some tracing and I saw that the first time you use a DatabaseContext in an application, it runs up the migration, and the migration configuration.
But, the first time the DatabaseContext is actually used (e.g. to load some data from the database) it will load your DbConfiguration class as well.
So I don't think there is any problem at all.

EntityFramwork generating Interfaces for MEF

I am playing around building some buildingblocks based on database tables.
So I've created an UsersManager and a ValidationManager both based on the EDMX "templates".
I'd really like to loose couple those two components with MEF. But therefore i need to create Interfaces of the entityobjects exposed in the ValidationManager.
Is there an easy way of creating those Interfaces, in that manner i can still use the EDMX generated classes?
Thanx,
Paul
Using an example of a database with a Product Table, is this what you're trying to achieve....
but still use generated entity classes (using either the standard EF generator or another POCO generator of some sort).
I'm not sure - as you mention MEF and I don't see it being directly related.
The generated entity classes are partial classes which will allow you to extend the generated class which in this case you want to extend to implement an interface.
Presuming the following interface is going to be used to introduce the layer of abstraction...
public interface IEntity {
public bool IsDeleted { get; set; }
}
Create a new class file with and extended Product class...
public partial class Product : IEntity {
public bool IsDeleted {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
}
You have now extended your generated entity Product with the partial class custom code - and you can use it as normal through EF.
Now instead of your UserManager and ValidationManager classes having a hard reference to Product, instead they'll only have reference to IEntity.
If I didn't understand the question, please provide more details on exactly it is you want to do.

Binding the interface with class in mvc3 EF

Suppose I have some Interface like :
public interface IIconComponent
{
// statements ...
}
then I am implementing this interface within my class as below
public class IconComponent : IIconcomponent
{
// implementing the interface statements ..
}
and creating a Table in mvc3 like:
public class IconDBContext : DbContext
{
public DbSet<IIconComponent> Icon {get; set;} //Is this statement possible
}
That is making the set of objects of interface type for storing the class IconComponent objects in the table. How to do this in MVC3 ?
Does I have to implement some model-binder for this ? or, there exists some other method ?
Thanking you,
EF doesn't support interfaces. DbSet must be defined with the real implementation. Once you change it to use implementation your actions will most probably use it as well because there will be no reason to work with abstraction.
Why would you use entity framework is you're creating abstraction layer on top of it, it's as you're not using entity framework at all and because of that entity framework is not able to work with interfaces.
If you really need to, you can let your Entity Framework classes implement interfaces. With POCO's it's straightforward, with edmx you can make partial classes that contain the derivation from the interface. However, as said by Ladislav, something like DbSet<IIconComponent> is not possible.
I can imagine scenarios where you would want to use this, e.g. dealing with other application components that only accept specific interfaces, but that you want to populate with your EF classes. (The other day, I did exactly that with a legacy UI layer).

Unity Container, Interface infinite loop

I need help with configuring MS Unity.
I have a class implementing an interface:
public class ProjectService : IProjectService
which works fine with this configuration:
_conainer.RegisterType<IProjectService, ProjectService>();
I another, caching, implementation, I need the first concrete type injected into the caching concrete type.
public class CachedProjectService : IProjectService
{
public CachedProjectService(IProjectService projectService, ICacheStorage cacheStorage)
{}
}
How can I configure Unity to return the caching version with the first implementation injected into it?
It's called decorators wiring that you can achieve like this :
_container.RegisterType<IProjectService, ProjectService>("innerService");
_container.RegisterType<IProjectService, CachedProjectService>(
new InjectionConstructor(
new ResolvedParameter<IProjectService>("innerService"),
new ResolvedParameter<ICacheStorage>()
));
Hope it helps