Importing dependencies using a class that inherits from Lazy<> - mef

Can you import using a class that inherits from Lazy rather than Lazy itself? I am exporting using a derivitive of ExportAttribute that contains metadata.
[FeatureExport(/* Feature Metadata Parameters */)]
public class Feature : IFeature
{
// Feature Properties
}
public class FeatureReference : Lazy<IFeature, IFeatureMetadata>
{
}
public class Consumer
{
[ImportMany]
public IEnumerable<FeatureReference> FeatureReferences { get; set; }
}
Is this possible? Would it work? I could try it myself, but I'm in development so I don't actually have any code written.

No, it won't work I'm afraid. You would need to implement your own programming model extension (either a custom part/catalog or possibly via ReflectionModelServices) to make this work.
MEF would have to create the FeatureReference object in order to set it, and considering that FeatureReference might have any constructor imaginable, you can guess why this isn't supported.

Related

PostSharp C# - How to Implement All Fields Required

PostSharp contracts make it easy to label individual fields as Required. But I want a class attribute that makes all of the class fields required. I'm guessing I would have to implement a custom aspect to support this.
It seems like it would be a common need for anyone passing around data containers. Can anyone direct me to some code that implements a custom "AllFieldsRequired" aspect in PostSharp?
You can implement PostSharp.Aspects.IAspectProvider:
public class AllFieldsRequiredAttribute : TypeLevelAspect, IAspectProvider
{
IEnumerable<AspectInstance> IAspectProvider.ProvideAspects(object targetElement)
{
Type type = (Type)targetElement;
return type.GetFields().Select(
m => new AspectInstance(m, new ObjectConstruction(typeof(RequiredAttribute))));
}
}
[AllFieldsRequired]
public class Foo
{
public string Bar;
public object Baz;
}

Get a list of multiple types using Entity Framework

Using MVC4 with Entoty Framework CodeFirst I am having problems with the following scenario:
public class Survey
{
public QuestionCollection Questions {get;set;}
}
public class QuestionCollection : List<IQuestion> //Just for MVC
{ }
public class QuestionType1 : IQuestion { ... }
public class QuestionType2 : IQuestion { ... }
Seems straightforward. Now in my controller I want to get the Survey so i have:
DataContext context = new DataContext ();
var survey = context.Surveys.Include(s => s.Questions).SingleOrDefault(s => s.Id == id);
It does compile but runtime it gives me the error:
A specified Include path is not valid. The EntityType 'Survey' does not declare a navigation property with the name 'Questions'.
What am I doing wrong here?
Is there any good tutorial on this topic?
Entity Framework Code First requires that navigation collections be declared as an ICollection<T>. Also, to enable lazy loading of the associations, it should be virtual. This is because, unless otherwise specified, EF will return a proxy object wrapping your declared class. Since your original QuestionCollection property is a concrete implementation, it can't override that in the proxy and enable the navigation. Questions has to be declared as the interface.
Your concerns and requirements in EF are different than in MVC, and they aren't always compatible. If you really, really wanted QuestionCollection, you'll have to map that.
Your Surveys entity should look like this:
public class Survey
{
public virtual ICollection<Question> Questions { get; set; }
}
Also, EF can't implement entity types declared as an interface. This won't work: public virtual ICollection<IQuestion> - your individual question types must all inheirit from a common abstract or concrete instance. They can still implement the interface, but your entity type properties cannot be declared that way.
I would highly recommend going through this series of blog posts on inheritance structures in
EF.
The way you would set up your questions entities would look like this:
// You can still keep the IQuestion interface around for MVC
public abstract class Question : IQuestion
{
// ... properties ...
}
public class QuestionType1 : Question
{
// ... properties ...
}
public class QuestionType2 : Question
{
// ... properties ...
}
public class Survey
{
// Note, collection of Question, not the interface.
public virtual ICollection<Question> Questions { get; set; }
}
Depending on how exactly you want your table structure to look, the base Question class may or may not be abstract. Refer to the above blog posts to see the various options - Table per Type, Table per Hierarchy, Table per Concrete.
Have a look at this link,I think you need to set some auto policies http://forums.asp.net/t/1816051.aspx/1

How to inject IEnumerable using Microsoft Unity IOC container

I have a Service that need inject more than one provider, see below for example. How to use Unity to implement this feature?
public class MyService: IMyService
{
public MyService(IEnumerable<Provider> Providers);
}
I know this is an old question, but maybe this will help someone else that stumbles upon this.
As long as you register the implementations with a specific name, this is possible to easily inject. You will then get all registered implementations.
public class MyService: IMyService
{
public MyService(IProvider[] providers)
{
// Do something with the providers
}
}
Just make sure to inject them as an array. Unity will understand this. And when you register them you can register them as such:
container.RegisterType<IProvider, FooProvider>("Foo");
container.RegisterType<IProvider, BarProvider>("Bar");
One way is to inject the UnityContainer itself, and then resolve all the Providers you need:
public class MyService : IMyService
{
public class MyService(IUnityContainer iocContainer)
{
var providers = iocContainer.ResolveAll<IProvider>();
}
}
The only thing you will need to do is register the UnityContainer with itself somewhere on setup:
unityContainer.Register<IUnityContainer>(unityContainer, new ContainerControllerLifetimeManager());

Entity Framework 3.5: change constructor of entities class

The default constructor in a generated Entity Framework Entities file is like this:
public ProjectEntities() : base("name=ProjectEntities", "ProjectEntities")
{
this.OnContextCreated();
}
I want to change it to:
public ProjectEntities() : base(UtilClass.GetEnvDependantConnectionStringName(), "ProjectEntities")
{
this.OnContextCreated();
}
This is because I want to have a different connection string for all the dev environments and the production environment, and have no chance they are mixed up (which is what my custom method checks).
How do I do that? This code is thrown away every time the designer file is regenerated.
You need to create another file alongside the auto-created ProjectEntities.Designer.cs, say ProjectEntities.cs. In that you use partial to extend the functionality of your entities class like this:
public partial class ProjectEntities : ObjectContext
{
partial void OnContextCreated()
{
this.Connection.ConnectionString = UtilClass.GetEnvDependantConnectionString();
}
}
The file won't then get changed when you regenerate the .Designer.cs file. You'll have to fetch the connection string yourself...
We fixed it by calling our entities ProjectEntitiesPrivate, and what was partial class ProjectEntities before, is now a non partial class ProjectEntities : ProjectEntitiesPrivate, with the constructor I need:
public class ProjectEntities: ProjectEntitiesPrivate
{
public ProjectEntities():base(UtilClass.GetEnvDependantConnectionStringName())
{
}
....

Found Possible Solution via SatisfyImports - Is There a Better Way?

Is there a better way to hook up dependencies??
This relies on the singleton App.Current and exposing a function that exposes the _container.SatisfyImports.
Is there a more MEF-tastic way of doing things?
Here is part of my main application class
public partial class App : Application
{
private CompositionContainer _container;
....
public void SatisfyImportsOnce(Object satifyMe)
{
_container.SatisfyImportsOnce(satisfyMe);
}
}
Here is a test class instantiated long after ComposeParts is called...
public class TestClass
{
public TestClass()
{
Console.WriteLine("Created a TestClass");
((Microsoft.Samples.XFileExplorer.App)App.Current).SatisfyImportsOnce(this);
}
}
I am in a similar situation in a WPF application where I want the MainWindow instance to import MEF exports. Since MEF does not create the MainWindow instance, it will not satisfy the imports unless you tell it to.
The way you are doing it will work if you do not want your instance to be registered for recomposition. If you do want recomposition, you should call ComposeParts.
Recomposition will update the imports in your class if and when they change.