1
我懷疑我沒有使用最佳實踐來使用Structure-Map。這樣可以使用StructureMap嗎? asp.net MVC 3
所有工作正常,但只是一個混亂的想法。
我的代碼看起來像這樣。
的Global.asax
IContainer container = new Container(
x => {
x.For<IUserRepo>().Use<UserRepo>();
x.For<IPostRepo>().Use<PostRepo>(); // this is the soultion for the error
});
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
PostController中
private readonly IPostRepo _postRepo;
public PostController(IPostRepo postRepo)
{
this._postRepo = postRepo;
}
StructureMapDependencyResolver
public class StructureMapDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public StructureMapDependencyResolver(IContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
object instance = _container.TryGetInstance(serviceType);
if(instance == null && !serviceType.IsAbstract)
{
_container.Configure(c => c.AddType(serviceType,serviceType));
instance = _container.TryGetInstance(serviceType);
}
return instance;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
}
這裏是IPostRepo貌似
public interface IPostRepo
{
bool CreatePost(Post newPost);
List<Post> ShowAllPosts();
Post FindPostById(int postId);
Post EditPost(Post editPost);
UserPostCommentViewModel FindAllPostComments(int postId);
int? AddPlusOneToNumberOfViews(int postId);
}
THX馬丁的幫助
ok ..讓我試試... n回覆你.. –
好的..一切都很好...當我嘗試去Postcontroller ..它給了我這樣的錯誤.. 沒有默認實例爲PluginFamily定義MBP_Blog.Interfaces.IPostRepo –
oops!當你得到IPostRepo時,我會告訴Structure-Map使用什麼。一切工作都像奶油一樣.... thx martin ... –