开发者

Using structuremap getinstance in linq statement with initializer values

I'm not sure how to ask this, but I want to create a new object in a linq statement, and initialize it's values. Since I have to use StructureMap's GetInstance method to get an instance of the object, I don't think this is possible. Am I wrong? And before we get off-topic, I realize I could probably create a constructor that takes the values I want to use, but I want to know if there's any way that I can do it with initializers an开发者_开发知识库d structuremap. I'm really weak on structuremap, and for all I know, there may be a simple way I'm just missing...

Thanks for any thoughts.

//basically, I'm creating a new object when I don't have an existing one for the groupid //conceptually, this is adding users to the selected groups if they don't already belong from g in GroupIDs where !OriginalGroups.Exists(ug => ug.SecurityGroupID == g) select StructureMap.ObjectFactory.GetInstance() {//initialize values of usertosecuritygroup};

//this is how I would do it if I wasn't relying on DI. from g in GroupIDs where !OriginalGroups.Exists(ug => ug.SecurityGroupID == g) select new UserToGroup {UserID = UserID, GroupID = g};


If you start using method chains rather than LINQ expressions you could do something like this:

    [TestFixture]
public class so_1
{
    public class UserToGroup
    {
        public int UserId { get; set; }
        public int GroupId { get; set; }
    }

    [Test]
    public void TEST()
    {
        var container = new Container();

        var groupIds = new int[] { 1,2,3,4,5};
        var originaGroups = new int[] { 4, 5 };

        var result = groupIds.Intersect(originaGroups).Select(group =>
        {
            var myClass = container.GetInstance<UserToGroup>();
            myClass.GroupId = group;
            return myClass;
        });

        result.First().GroupId.ShouldEqual(4);
        result.Skip(1).First().GroupId.ShouldEqual(5);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜