我怀疑我没有使用最佳做法来使用Structure-Map。
所有工作正常,但只是一个混乱。
我的代码看起来像这样。
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));
private readonly IPostRepo _postRepo;
public PostController(IPostRepo postRepo)
{
this._postRepo = postRepo;
}
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>();
}
}
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);
}
马丁为你提供帮助
答案 0 :(得分:1)
没有。就像我在你的另一个问题中说的那样,取出Controller Activator ...除非你是出于某种目的使用它(它看起来不像你)。
此外,这一行很简单:
x.ForRequestedType<AccountController>().TheDefault.Is.
ConstructedBy(() => new AccountController(new UserRepo()));
您不应该将new
用于UserRepo
...这就是上述行所处理的内容:
x.For<IUserRepo>().Use<UserRepo>();
如果你取出了ControllerActivator,你应该有一个很好的MVC应用程序开始。